gefvert.org

PowerShell Reference

2020-10-07

Commands

Command Alias Comment
 
'string' String literal, not expanded
"string=$a" String literal with variable expansion
"math=$(2+3)" Embedded calculation
"result=$($value)" Embedded variable
1, 2, 3 Array literal
1..100 Array sequence literal
# Comment
& Call operator: $a = 'dir'; & $a
. Call operator in local scope: $a = 'dir'; . $a
 
$_ Current object in foreach
$^ First token
$$ Last token
$? Success or fail of last statement
$Args
$Foreach Enumerator in foreach loop
$Home Home directory
$Input Input piped to a function or block
$Match Hash table of matches found by -Match
$LastExitCode Last exit code of native application
$true Boolean TRUE
$false Boolean FALSE
$null Null object
 
Execution policy
Set-ExecutionPolicy Set-ExecutionPolicy RemoteSigned is recommended
 
Help
Get-Commands List all commands
Get-Help help Get-Help command [-Online] [-Full]
Update-Help Run as administrator
 
Filters
Where-Object ?, where dir -recurse | ? {$_.extension -eq ".txt}, new syntax = dir -recurse | ? extension -eq ".txt"
Foreach-Object %, foreach foreach ($var in $list { ... }
 
Files
Clear-Item cli Clear an item/file (but don't delete)
Copy-Item cp, copy
Get-Content cat, gc
Get-Item gi Get information about an item/file
Move-Item mv
New-Item ni
Remove-Item del, rm, rmdir
Rename-Item rn
Set-Content sc
 
Directories
Get-ChildItem dir, ls, gci Get-ChildItem -Path c:\example -Filter 'Foo*' [-Recurse] [-Include filespec] [-ErrorAction SilentlyContinue]
Get-Location gl, pwd
Push-Location pushd
Set-Location cd
Test-Path Test if a file/dir exists
 
Output
Clear-Host cls, clear
Format-Hex fhx
Format-List fl
Format-Table ft
Format-Wide fw
Out-File Pipe output to file: ls | Out-File test.txt [-Append]
Write-Output echo
 
Variables
$a,$b = 1,2 Deconstruction assignment
Clear-Variable clv
Get-Variable gv
Measure-Object Calculates Count, Sum, Average, Maximum and Minimum
New-Object select New-Object System.Net.WebClient
Select-Object select Get-Host | select Version
Select-String Searches for text in items
Set-Variable set, sv set a 2, set a 2 -Option constant, set a 2 -scope global, $a=2, $global:a=2
Sort-Object sort
 
Matches
-Match Match wildcards: ls | where {$_.name -match "net*"} - can also take regular expression components like \w, \s, and \d
-Like Like -Match, but operates on the whole string, not just part of it
-Contains Requires exact match
-NotMatch ls | where {$_.name -match "network"}
-NotLike
-NotContains
-And, -Or, -Not Logical tests
-Eq, -Ne, -Gt, -Lt, -Ge, -Le Equality comparison
-Replace Select-String -Path test.txt -Pattern Mine | foreach {$_ -Replace "Mine", "Yours"}
-CReplace Case sensitive replace
 
Date/Time
Get-Date ([System.DateTime]"2020-01-04").DayOfYear or (Get-Date).DayOfYear
 
Network
Test-Connection Seems oddly faulty sometimes
 
Processes
Get-Process List all processes
Start-Process start Start-Process -ProcessName my.exe or Start-Process "https://google.com"
Stop-Process Stop-Process 9212 or Stop-Process -ProcessName lync

Examples

Find all errors in Windows log files:

$files = Get-ChildItem "c:\windows" -Recurse -Include "*.log" -ErrorAction SilentlyContinue
$files | Select-String "Error" -ErrorAction SilentlyContinue | Group-Object filename | Sort-Object count -Descending

List disk drives:

$disks = Get-WmiObject Win32_LogicalDisk
foreach ($drive in $disks) { "Drive = " + $drive.Name }

Math

$n = 13
$i = 1
do {
    $i * $n; $i++
} while ($i -le 20)

Loops

ForEach ($item in $list) {
    ...
}

For ($i=1; $i -le 100; $i++) { $i }

Conditionals

If (test) {
    ...
}
ElseIf (test) {
    ...
}
Else {
    ...
}

If ($Number -gt 0) {"Bigger than zero"}

If (-Not $Service) { $Name + " is not installed on this computer." }

$i =1
$ip = "192.168.1."
Write-Host "IP Address"
Write-Host "----------------------------------------"
Do { 
    $ip4th = $ip + $i
    $pingy = Get-WmiObject Win32_PingStatus -f "Address='$Ip4th'"
    If ($pingy.StatusCode -eq 0) {
        "{0,0} {1,5} {2,5}" -f $Pingy.Address, $Pingy.StatusCode," ON NETWORK"
    }
    Else {
        "{0,0} {1,5} {2,5}" -f $Pingy.Address, $Pingy.StatusCode, " xxxxxxxxx"
    }
    $i++
}
Until ($i -eq 20)

Switch statement

$disk = Get-WmiObject win32_logicaldisk
Foreach ($drive in $disk) {
    Switch ($drive.DriveType) {
        1 { $drive.DeviceID + " Unknown" }
        2 { $drive.DeviceID + " Floppy or Removable Drive" }
        3 { $drive.DeviceID + " Hard Drive" }
        4 { $drive.DeviceID + " Network Drive" }
        5 { $drive.DeviceID + " CD" }
        6 { $drive.DeviceID + " RAM Disk" }
    }
}

Switch -Wildcard ($_.entrytype) {
    "err*"  { $errors++ }
    "warn*" { $warnings++ }
    "info*" { $info++ }
    default {}
}

Functions

function Start-PSAdmin { Start-Process PowerShell -Verb RunAs }

function Get-NewPix {
    $start = Get-Date -Month 1 -Day 1 -Year 2010
    $allpix = Get-ChildItem -Path $env:UserProfile\*.jpg -Recurse
    $allpix | Where-Object { $_.LastWriteTime -gt $start }
}

function Add-Numbers($one, $two) { $one + $two }

function Get-Extension { $args[0] + ".txt }
Get-Extension mytextfile

# Piping elements
function Process-Pipeline
{
    begin { "Starting input" }
    process { "Processing: $_" }
    end { "The end." }
}

Static parameters

Param(
    [String[]] $Delimiters,
    [String] [Parameter(Mandatory)] $Name,
    [Switch] $Production = $false,
)

Make an OAuth2 POST request

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
$authorization = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($ClientId + ":" + $ClientSecret))
$headers = @{
    'Authorization' = "Basic " + $authorization;
    'Accept' = 'application/json' 
}

$result = Invoke-WebRequest -Headers $headers -Uri "https://$($environment)/oauth/token" -Method 'POST' -Body ("grant_type=authorization_code&code=" + $Code)