Math & Comparison
Supported
- +, -,
*, /, %
Powershell do not use == or !=, <=
(1 -eq 2)-ge/le/gt/lt- common comparison, greater/less than or equal to- by adding
cintoeqwill make the search case sensitive
File based operation with `Test-Path
Test-Path $filePath- whether a folder or file exist
If/Else
if(condition){ action } elseif(){} else {}- uses
()for condition and{}for action
(-not $true) # negate a condition
($true -and -or $false) # multiple conditionsSwitch
Where there are many conditions
switch($variable){
"value" {action; break}
"value2" {action2; break}
default {defaultAction}
}- similar to dictionary, the lines can be shortened with
; - best practice to put
breakso only 1 case executes
If the switch statement need a conditional with $variable, use {$_}
switch($variable){
{$_ -eq 123} {action}
}Try catch will only catch terminating error
try{ failed } catch { echo failed }To adjust error types of some commands
command -ErrorAction $- continue - will keep executing and show error
- ignore - continue and not show anything
- inquire - ask the user what to do
- silentlycontinue - store into error variable and continue
- stop - stop executing the script
- break - enter debug mode (VSCode)
Get Exception message
$_.Exception.MessageRaise an error
throw "custom error"Change default error action (similar to `set -e)
$ErrorActionPreference = "Stop"Errors are stored in a variable $Error
- the latest error is stored in the first index `$Error[0]