Thursday, July 2, 2015

Powershell Useful Command Collection

C:\>runas /user:<DomainName>\<AdministratorAccountName> cmd

**************************REMOTE ACCESS******************************

Remote Session (Requires Powershell 3.0)
Enter-PSSession hostname

Enable WINRM on Windows 7
The WinRM service is configured for manual startup by default. You must change the startup type to Automatic and start the service on each computer you want to work with. At the PowerShell prompt, you can verify that the WinRM service is running using the following command: 
Get-Service -Name WinRM -ComputerName NAME
The value of the Status property in the output should be “Running”.

To configure Windows PowerShell for remoting, type the following command: 
Enable-PSRemoting –force

*****************************STANDARD STUFF***************************

Start a service on a remote computer
Get-Service -ComputerName CNUMBER -name SERVICENAME | Start-Service

To Install Windows Administrative Tools
Install-WindowsFeature RSAT-Feature-Tools

Check local Administrators group members
Net localgroup administrators

Get Newest 10 events in eventlogs
get-eventlog -LogName Security (or other log name) -Newest 10

Get Eventlog events on remote computer, amount of events, per eventID, formated to a table.
$Machine = "LocalHost"
Get-Eventlog -Logname System -ComputerName $Machine -newest 1000 | 
Where-Object {$_.EventID -lt '100'} | 
Format-Table MachineName, Source, EventID -auto

Get Running Services from another computer
Get-Service -ComputerName HOSTNAME |where-object {$_.Status -eq "Running"}

Get Running Process from another computer
Invoke-Command -ComputerName HOSTNAME -ScriptBlock {Start-Process NAME}

Last Boot time of remote server

$LastBootUpTime = Get-WmiObject Win32_OperatingSystem -Comp HOSTNAME | Select -Exp LastBootUpTime

Last Boot time of remote server

Get-WmiObject Win32_OperatingSystem -computer HOSTNAME | Select CSNAME @{N='LastBoot';E={[System.Management.ManagementDateTimeCOnverter]::ToDateTime($_.LastBootUpTime)}}

Last Boot time of local server

PS C:\> $wmi = gwmi win32_operatingsystem
PS C:\> $wmi.ConvertToDateTime($wmi.LastBootUpTime)
Friday, August 22, 2014 4:39:23 AM

Get last boot time

Get-CimInstance -ClassName win32_operatingsystem | select csname, lastbootuptime

Restart a remote computer
Restart-Computer -ComputerName HOSTNAME -Force

****************************BIT LOCKER********************************

Bitlocker Drive Status
Manage-dbe -status

***************************SCCM Configuration Manager******************

Get last three items of SCCM SMSPXE log
get-content -Path "\\server\drive$\Program Files\Microsoft Configuration Manager\Logs\SMSPXE.log" -Tail 3

Get installed application list on hostname
Get-WmiObject -ComputerName  HOSTNAME -class Win32_product
Get-WmiObject -ComputerName  HOSTNAME -class Win32Reg_AddRemovePrograms (SCCM Client Only)

Get any USB storage devices attached to your computer
Get-WmiObject -Class Win32_PnPEntity | Where-Object { $_.DeviceID -like 'USBSTOR*' }
IN WMI Query
Get-WmiObject -Query 'Select * From Win32_PnPEntity where DeviceID Like "USBSTOR%"

This command will return the total number of bytes of the 32 largest files in the folder without listing the file names.

$big32 = Get-ChildItem C:\Users\ -recurse | Sort-Object length -descending | select-object -first 32 | measure-object -property length –sum
$big32.sum /1gb

***************ACTIVE DIRECTORY ********************************

Get add AD Users like "*shawn*" and formats list

Get-ADUser -Filter 'SamAccountName -like "*shawn*"' | FT SamAccountName -A

Get-ADUser -Filter 'SamAccountName -like "*shawn*"' | FT SamAccountName,GivenName,Name -A

SamAccountName GivenName Name              
--------------                ---------          ----              
shawn                        Shawn       Shawn Dunham      
shawnwise                Shawn       Shawn Dunham - Wise
shawntest                 Shawn       Shawn Dunham Test 

Get-AD User Name like "Dunham"
Get-ADUser -Filter 'Name -like "*Dunham"' | FT

Disting Enabled GivenNa Name    ObjectC ObjectG SamAcco SID     Surname UserPri
uishedN         me              lass    UID     untName                 ncipalN
ame                                                                     ame   
------- ------- ------- ----    ------- ------- ------- ---     ------- -------
CN=M...    True Marg... Marg... user    ca01... 60146   S-1-... Kobe    6014...
CN=D...    True Daniel  Dani... user    9931... 91620   S-1-... Kobe    9162...

Get-AD Computers (servers) like windows server) and total numbers
Get-ADComputer -LDAPFilter "(OperatingSystem=*windows server*)" | Measure-Object

Count    : 605
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

Get-ADUser Created and Modified Dates
Get-ADUser 'shawn' -Properties Created,Modified | Select-Object Name,Created,Modified | Sort-Object Created

Get-ADUsers Created 7 days before today's date. Export to CSV
$When = ((Get-Date).AddDays(-7)).Date
Get-ADUser -Filter {whenCreated -ge $When} -Properties whenCreated | Export-Csv C:\Myscripts\GetDateCreated.csv


Open Web Page
#requires -Version 2

function Show-WebPage
        [Parameter(Mandatory = $true, HelpMessage = 'URL to open')]

    Start-Process -FilePath iexplore.exe -ArgumentList $URL

Create “Task Kill” Application

With just one pipeline command, PowerShell can open a list of running applications. You can then select one or more in the list (hold CTRL to select more than one), and PowerShell would kill the selected applications.

Get-Process |
  Where-Object { $_.MainWindowHandle -ne 0 } |
  Select-Object -Property Name, Description, MainWindowTitle, Company, ID |
  Out-GridView -Title 'Choose Application to Kill' -PassThru |
  Stop-Process -WhatIf

Note how the code uses –WhatIf to only simulate the kill. Remove –WhatIf to actually kill applications.
Killing applications will stop the selected applications immediately. All unsaved data is lost.

Moving Outdated Log Files to Archive

Occasionally, you may want to move files to an archive folder when they are older than a given number of days.
Here is an example that illustrates the basic strategy on how to identify outdated files, and how to move them to an archive:

#requires -Version 1
# how old (in days) would obsolete files be
$Days = 14

# where to look for obsolete files
$Path = $env:windir
$Filter = '*.log'

# where to move obsolete files
$DestinationPath = 'c:\archive'

# make sure destination folder exists
$destinationExists = Test-Path -Path $DestinationPath
if (!$destinationExists)
    $null = New-Item -Path $DestinationPath -ItemType Directory

$cutoffDate = (Get-Date).AddDays(-$Days)

Get-ChildItem -Path $Path -Filter $Filter -Recurse -ErrorAction SilentlyContinue |
Where-Object -FilterScript {
    $_.LastWriteTime -lt $cutoffDate
} |
Move-Item -Destination c:\archive -WhatIf

The example script looks for log files with the extension *.log inside the Windows folder and all of its subfolders. Any log file older than 14 days (defined as not being modified within the past 14 days) is moved to c:\archive. This folder is created if it does not yet exist.
Note that this is only an example. You would need Administrator privileges to actually move files out of the Windows folder.