Professional Documents
Culture Documents
Strings
Flow Control
"$varexpand"
Stringwithexpansion"
If($xeq5){}Elseif$xgt5 Else
If
dirC:\pub|whereobjectLastWriteTimegt(GetDate).addDays(1) FilesinC:\pubwithlastwritetimegreater
thanyesterday
'$varnoexpand'
Stringwithnoexpansion'
$x=1;while($xlt10){$x;$x++}
While
@"
HereString
"@
HereString quotes,
expressions,etc.Single
quotesfornoexpressions
For($i=0;$ilt10;$i++){$i}
For
Foreach($fileindirC:\){$file.Name}
Foreach
1..10|foreach{$_}
Foreach
psExplorer|selectobjectPropertyProcessNameExpandProperty Getexplorerprocesses,selectprocessname,
Modules|formatlist
expandmodulespropertyarray
Switchoptions(<valuestoswitchon>){
PatternX{statement}
Default{DefaultStatement}
Switch
ps|SortObjectPropertyWorkingSet|SelectObjectLast5
SortProcessesbyworkingset,selectlast5
"a","b","a"|SelectObjectUnique
Returnonlyunique returns@(ab)
GetService|GroupObjectStatus
GroupservicesbytheirStatus
dir|GroupObject{$_.Lengthgt100KB}
Groupobjectsbigger/smallerthan100KB
GetContentC:\pcs.txt|SelectString"q"|sls"win7"
Selectstringswith"q","win7"frompcs.txt
ps|FormatTablePropertyName,StartTimeAutoSize
FormatpsoutputshowingName,StartTime
properties,autosizethetable
Variables
$var="string"
Assignvariable
[Type]$var="typedVar"
Assignstrongtypedvariable
[ValidateRange(1,9)][int]$x=1
Assignstrongtypedattribute
controlledvariable
$a,$b,$c=0or$a,$b='a','b'
Assignmultiplevariables
#Comment
$a,$b=$b,$a
Flipvariables
<#comment # Multilinecomment
Scopes
global,local,privateorscript
Comment
"A`"test`""
Escapechar`
ps|whereobject{$_.pathlike"C:\windows\system32*"and
$_.companynotlike"Microsoft*"}
Processeswherepathincludessystem32and
companydoesn'tstartwithMicrosoft
=,+=,=,*=,/=,%=,++,
Assignoneormorevaluestovariable
and,or,xor,not,!
Connectexpressions/statements
eq,ne
Equal,notequal
Arrayofstrings
gt,ge
Greaterthan,greaterthanorequal
@()
Emptyarray
lt,le
Lessthan,lessthanorequalto
ps|FormattableProcessName,@{Label="TotalRunTime";
Expression={(GetDate) $_.StartTime}}
Tableshowingprocessname,custom
label/expressionshowingruntime.
1,(2,3),4
Arraywithinarray
replace
Replacement HireplaceH,P
GetEventLogLogSystem|Selectfirst5|Formattablewrap
Getfirst5eventsinsystemlog,wrapdisplay
,"hi"
Arrayofoneelement
match,notmatch
Regularexpressionmatch
giC:\Users|formatlistproperty*
GetallpropertiesfromC:\usersinlistformat
$arr[5]
Sixthelementofarray
like,notlike
Wildcardmatching
"{0}`t{1]`n"f$a,5
foperatortoconstructstrings.{0}replaced
with$a,{1}with5etc.
$arr[2..20]
Returnelements3thru21
$arr[1]
Returnlastarrayelement
$arr[3..1]
$global:var="var"
Assignglobalscopedvariable
Arrays
"a","b","c"
`t
Tab
`n
Newline
Linecontinuation
$arr[1,4+6..9]
@(GetProcess)
Elementsatindexpositions1,4,6to9
Forceresulttoanarray
$arr[($arr.length1)..0] Reversearray
$arr[1]+=200
$b=$arr[0,1+3..6]
$z=$arrA+$arrB
Addtoexistingarrayitemvalue
Newarrayfromelementsof$arrarray
Combinetwoarraysintosinglearray
Createemptyhashtable
Create,initializehashtable
[ordered]@{a=1;b=2;c=3}
Createordereddictionary
$hash.key1=1
Assign1tokeykey1
$hash.key1
Returnvalueofkey1
$hash["key1"]
Returnvalueofkey1
$hash.GetEnumerator|sortKey SorthashtablebyKey
[pscustomobject]@{x=1;z="z"}
Createcustomobject
GetLocation
Getcurrentdirectory
SetLocation
Changedirectory
GetContent
Getcontentoffile
AddContent
Appendcontent
SetContent
Setcontentoffile
OutFile
Formattedtexttofile
Other Operators
OutNull
Discardoutput
Split
OutString
Converttostrings
CopyItem
contains,notcontains TRUEifvalueonrightinarrayonleft
Common commands
PSDrives
GetEventLog
GetWinEvent
Alias:
Aliasesincurrentsession
GetCimInstance
GetDate
Cert:
Certificatestoreforuser
Splitastringabcdefghisplitde
StartSleep
CompareObject
Env:
Environmentvariables
join
Joinsmultiplestringsabc,defjoin;
StartJob
GetCredential
Function:
Allfunctionsincurrentsession
Copyitems
..
Rangeoperator1..10|foreach{$_*5}
TestConnection
NewPSSession
HKLM:
HkeyLocalMachineHive
RemoveItem
Removeitems
is,-isnot
Boolean isobjectinstanceofspecified.NETtype
TestPath
SplitPath
HKCU:
HkeyCurrentUserHive
MoveItem
Moveitems
as
Convertinputobjecttospecified.NETtype
Variable:
Variablesinthecurrentsession
RenameItem
Renameitem
Formatstrings1..10|foreach{"{0:N2}"f$_}
WSMan:
WinRMconfiguration/credentials
SetItem
Setcontentsoffile
[]
Castoperator.[datetime]$birthday="1/10/66"
AD:
ActiveDirectory
Clearitem
Clearcontentsoffile
$()
Subexpressionoperator
NewItem
Newemptyfileordir
@()
Arraysubexpressionoperator
&
Thecall/invocationoperator.
in,notin
Reverseofcontains,notcontains
ImportCliXML
ConvertToXML ConvertToHTML
ExportCSV
ImportCSV
ConvertToCSV
ConvertFromCSV
DatepropertyofobjectfromGetDate
GetDate|GetMember
Listpropertiesandmethodsofobject
[DateTime]::Now
Staticpropertiesreferencedwith"::"
"string".ToUpper()
UseToUpper()Methodonstring
[system.Net.Dns]::GetHostByAddress("127.0.0.1") Usestaticmethodtogethostnamewith"::"
$excel=newobjectcomexcel.application
CreateanewExcelCOMobjecttoworkwith
gcivariable:
Variablesincurrentsession
Regular Expressions
Objects
(GetDate).Date
SetlocationHKLM: HKLMRegistryhive
Automatic variables
\w
Anywordcharacter[azAZ09]
$_,$PSItem
Currentpipelineobject
\W
Anynonwordcharacter
$Args
Scriptorfunctionarguments
\s
Anywhitespacecharacter
Errorsfromcommands
\S
Anynonwhitespacecharacter
$True,$False Booleanvaluefortrue,false
\d\D
Anydigitornondigit
$null
Empty
{n}{n,}{n,m} Matchnthroughminstancesofapattern.
$profile
Arrayofprofilelocations
More
$Error
Google.NETRegularExpressions