PowerShell C heat S heet
PowerShell C heat S heet v 2
Adapted w ith p ermission f rom B en P earce’s O riginal.
Essential C ommands
Setting S ecurity P olicy
To g et h elp o n a ny c mdlet u se g et-‐help
View a nd c hange e xecution p olicy w ith G et-‐
Get-Help Get-Service
Execution a nd S et-‐Execution p olicy
To g et a ll a vailable c mdlets u se g et-‐command
Get-Executionpolicy
Get-Command
Set-Executionpolicy remotesigned
To g et a ll p roperties a nd m ethods f or a n o bject u se g et-‐member
Get-Service | Get-Member
Functions
Parameters s eparate b y s pace. R eturn i s
To E xecute S cript
optional.
function sum ([int]$a,[int]$b)
powershell.exe –noexit &”c:\myscript.ps1”
{
return $a + $b
Variables
Arrays
}
sum 4 5
Must s tart w ith $
To i nitialise
$a = 32
$a = 1,2,4,8
Can b e t yped
To q uery
True / F alse / N ull
[int]$a = 32
$b = $a[3]
Set a V ariable t o t rue
$a = $true
Check i f a V ariable i s f alse
Constants
If ($b –eq $false)
Created w ithout $
Is i t n ull?
Set-Variable –name b –value 3.142 –option constant
If ($c –eq $null)
Referenced w ith $
$b
Creating O bjects
To c reate a n i nstance o f a c om o bject
New-‐Object -‐ comobject < ProgID>
$a = New-Object –comobject "wscript.network"
$a.username
To c reate a n i nstance o f a . Net F ramework o bject. P arameters c an b e p assed i f r equired
New-‐Object – type < .Net O bject>
$d = New-Object -Type System.DateTime 2006,12,25
$d.get_DayOfWeek()
Writing t o C onsole
Capture U ser I nput
Variable N ame
Use R ead-‐Host t o g et u ser i nput
$a
$a = Read-Host “Enter your name”
or
Write-Host "Hello" $a
Write-Host $a –foregroundcolor “green”
Miscellaneous
Line B reak `
Passing C ommand L ine A rguments
Get-Process | Select-Object `
name, ID
Passed t o s cript w ith s paces
Comments #
myscript.ps1 server1 benp
# code here not executed
Accessed i n s cript b y $ args a rray
Merging l ines ;
$servername = $args[0]
$a=1;$b=3;$c=9
$username = $args[1]
Pipe t he o utput t o a nother c ommand |
Get-Service | Get-Member