General Info

Information

# Available modules
PS> Get-Module -ListAvailable

# Find modules
PS> Find-Module -Tag <tag>

# Import modules
PS> Import-Module <module>

# View commands
PS> Get-Command *
PS> Get-Command -Module <module>

# View alias
# -> cmd commands are aliases so switches don't work
PS> Alias
PS> New-Alias <name> <command>

# PS version
PS> Get-Host
PS> $psversion

# Computer information
PS> Get-CimInstance -ClassName Win32_[Desktop/BIOS/Processor/...]

# Help
PS> Get-Help <command>
PS> Update-Help

# Change prompt
Function prompt {“PS> “}

Commands

# Basics
PS> New-Item -Name <name> -ItemType <type|directory> -Path <dir>
PS> Remove-Item [-Force] [-Recurse] # alias dir
PS> Get-Content # alias cat
PS> Get-ChildItem [-Path <path>] [-Hidden] [-Recurse] # dir/ls
PS> $PSItem # current item

# Processes
PS> Start-Process [-FilePath C:\\...] <process>[,<*process*>]
PS> Get-Process <process>[,<*process*>]
PS> Stop-Process <process>[,<*process*>]

# Services
PS> Get-Service
PS> Start-Service
PS> Suspend-Service
PS> Resume-Service
PS> Stop-Service
PS> Restart-Service

# Users & Groups
PS> Get-LocalUser # list all
PS> Get-LocalUser <user> | Format-List -Property *
PS> $password = ConvertTo-SecureString -String <password> -AsPlainText -Force
PS> New-LocalUser -Name <user> -Password $password
PS> New-LocalUser -Name <user> -Password (Read-Host "Password" -AsSecureString)
PS> Set-LocalUser -Name <user> -Description <desc>

PS> Get-LocalGroup
PS> Get-LocalGroup <group> | Format-List -Property *
PS> New-LocalGroup -Name <group>
PS> Set-LocalGroup -Name <group> -Description <desc>

PS> Get-LocalGroupMember -Name <group>
PS> Add-LocalGroupMember -Group <group> -Member <user>

# Network
PS> Invoke-WebRequest -Uri <file-url> -OutFile <file.ext> # wget ; IWR
PS> Invoke-Expression(New-Object Net.WebClient).downloadString('<https://URL/file.exe>') #IEX ; download and execute (if text file, run commands in file)

# Base64
PS> [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes("<thing>")) # also UTF8, ASCII, ...
PS> [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('<b64==>'))
PS> powershell.exe -nop -enc <b64==> 

# Hashes
PS> Get-Filehash <file>
-algorithm [md5/sha1]

# Other
PS> Compare-Object -ReferenceObject <object1> -DifferenceObject <object2> -Property <prop>
PS> Measure-Object [-Word] # count, avg, [word count]...

# Clipboard
PS> Set-Clipboard -Value <value>
PS> Get-Clipboard
PS> <command> | clip

# Where / PSItem
PS> Get-Process | Where-Object {$PSItem.name -eq "notepad"} | Stop-Process
PS> Get-Process | Where-Object {$_.name -eq "notepad"} | Stop-Process # same
PS> Get-Process | Where-Object name -eq "notepad" | Stop-Process # same
PS> Get-Process | ? name -eq "notepad" | Stop-Process # same

PS> Get-Process | Where-Object -Property Status -eq "Stopped"

# comparators: gt, ge, lt, le, eq, ...
# properties: name, length, ...

# Loops
| ForEach { }
| %{ } # same

# Piping
| Sort-Object
| Select-Object <property1>,<property2>,...
| ForEach-Object
| Get-Member # object properties, events, methods
| Measure-Object # count/stats

# User Input
PS> $var = Read-Host -Prompt '<Question to ask the user>'

# Output
| Format-[List/Table] [*] # * adds more info
> <file.txt>
>> <file.txt>

# Variables
$vararray = <command> # e.g. "Get-Content <file>"
"<search-phrase>" -in $vararray
$servers -like "*<search-phrase>*" # inc wildcards
$vararray -ne <search-phrase> # not equal, set $var= to remove
$vararray[1] # second value

# Operators
<command1> && <command2> # do second if first succeeds
<command1> || <command2> # do second if first fails
<command1> ; <command2> # do both

# Conditionals
<if-statement> ? <if-true> : <if-false>
if <if-statement> { <if-true> } else { <if-false> }

Examples & Useful

PS> Get-AdUser -filter * -Properties "LastLogonDate"
 | Where-Object {$_.LastLogonDate -le (Get-Date).AddDays(-60)}
 | Sort-Object -Property LastLogonDate -Desc
 | Format-Table -Property Name, LastLogonDate -AutoSize
 | Disable-AdAccount -WhatIf # must not use Format-Table before

PS> Get-Process | Sort WS -Desc | Select -First 10 > Top10Memory.txt

PS> $Servers | Where-Object { $_ -like "*SVR*" }
 | ForEach-Object { Write "Found $_, performing maintenance" }
 | Out-File -FilePath "C:\\Class\\Maintenance.txt"

PS> Get-ChildItem *.mkv | ForEach { Write-Host $_.Name }

PS> Get-ChildItem -Filter "*.<ext>" | Move-Item -Destination <dir>

$names = Get-Content files.txt # new file names
Get-ChildItem <dir>\\*.<ext> | ForEach {$i=0} {Rename-Item $_ ($_.basename + $names[$i++] + $_.extension)}

# Cybrary lab about networking
PS> Install-Module -Name LoopbackAdapter -Force
PS> New-LoopbackAdapter -Name "LabNet1"
PS> Get-NetAdapter -Name LabNet1 | Format-List -Property *
PS> New-NetIPAddress -InterfaceAlias LabNet1 -IPAddress 10.0.1.51 -PrefixLength 24 -DefaultGateway 10.0.1.1
PS> Set-DnsClientServerAddress -InterfaceAlias LabNet1 -ServerAddresses 10.0.0.1

PS> Get-DNSClientGlobalSetting
PS> Set-DNSClientGlobalSetting -SuffixSearchList "microsoft.com","bing.com","hotmail.com"
PS> NSLookup www # should include e.g. www.microsoft.com

# Snapshop registry
dir -rec -erroraction ignore HKLM:\\ | % name > Current-HKLM-$(get-date -f yyyy-MM-dd).txt
dir -rec -erroraction ignore HKCU:\\ | % name > Current-HKCU-$(get-date -f yyyy-MM-dd).txt
Compare-Object (Get-Content -Path .\\Base-HKCU.txt) (Get-Content -Path .\\[current_snapshot_file_name])

Resources

johnthebrit/PowerShellMC