PowerShell Cheat Sheet

Cheat sheet of common PowerShell syntax and commands.

Comments
Multi-line comment
A multi-line comment starts with a <# and ends with a #>.
<#
This is a comment
#>
Single line comment
A single line comment starts with a #.
#This is a comment
Loops
For loop
Standard for loop incrementing from 0 to 99
for([int]$i = 0; $i -lt 100; $i++)
{
   $t = $i
}
Foreach loop
Standard foreach loop iterating over an array of strings
param([string[]]$strings)
foreach ($item in $strings)
{
   $str = $item
   continue
}
While loop
Standard while loop that breaks immediately.
while ($true)
{
   break
}
Processes
Get Processes
Returns a list of processes or a process by name or ID
Get-Process
Get-Process -Name "myProcess"
Get-Process -Id 1
Start Process
Starts a process with the specified arguments
Start-Process -FilePath "Notepad.exe" -ArgumentList "test.txt"
Strings
Literal string
A literal string does not expand variables within it when evaluating.
$str = 'This is a literal string'
Expandable string
An expandable string expands variables within it when evaluating.
$str = "This is a $adjective string"
Syntax
Cast
Cast a value from one type to another
$myInt = 1
$myLong = [long]$myInt
Operators
Common boolean operators
$eq = 1 -eq 2
$notEq = 1 -ne 2
$or = 1 -eq 2 -or 2 -eq 1
$and = 1 -eq 2 -and 2 -eq 1
$gt = 1 -gt 2
$lt = 1 -lt 2
$ge = 1 -ge 2
$le = 1 -le 2
$plus = 1 + 1
$minus = 1 - 1
$bor = 1 -bor 1
Create object
Creates an object based on the specified type
New-Object -TypeName System.Object -ArgumentList $myVariable
Try, catch, finally
Exception handling structures.
try
{
   $item = (New-Object -TypeName object)
}
catch [Exception]
{
   $item = (New-Object -TypeName object)
}
catch
{
   $item = (New-Object -TypeName object)
}
finally
{
   $item = (New-Object -TypeName object)
}
Indexer
Indexer
param([string]$str)
$item = $str[3]
Array initializer
Initializes an array
$arr = @("my","strings")
If, else, else if
Standard conditional logic.
if (1 -eq 2)
{
}
elseif ("xyz" -eq ((New-Object -TypeName Object)))
{
}
else
{
}