You are on page 1of 1

Strings Flow Control Filter, Sort, Group and Format (aliases for brevity)

PowerShell Cheat Sheet "$var expand" String with expansion " If($x ­eq 5){} Elseif$x ­gt 5  Else  If dir C:\pub | where­object LastWriteTime ­gt (Get­Date).addDays(­1) Files in C:\pub with lastwritetime greater 


than yesterday
'$var no expand' String with no expansion ' $x = 1; while($x ­lt 10){$x;$x++} While
Variables ps | where­object {$_.path ­like "C:\windows\system32*" ­and  Processes where path includes system32 and 
@" Here­String ­ quotes,  For($i=0; $i ­lt 10; $i++){ $i } For
$var = "string" Assign variable $_.company ­notlike "Microsoft*"} company doesn't start with Microsoft
Here­String expressions, etc. Single 
Foreach($file in dir C:\){$file.Name} Foreach
[Type]$var="typedVar" Assign strong typed variable "@ quotes for no expressions ps Explorer | select­object ­Property ProcessName ­ExpandProperty  Get explorer processes, select processname, 
1..10 | foreach{$_} Foreach Modules | format­list expand modules property array
[ValidateRange(1,9)][int]$x=1 Assign strong typed attribute 
controlled variable Comments, Escape Characters, Backtick Switch ­options (<values to switch on>){ Switch ps | Sort­Object ­Property WorkingSet | Select­Object ­Last 5 Sort Processes by workingset, select last 5
PatternX {statement}
$a,$b,$c = 0 or $a,$b = 'a','b' Assign multiple variables #Comment Comment "a","b","a" | Select­Object ­Unique Return only unique ­ returns @(a b)
Default {Default Statement}       
$a,$b = $b,$a Flip variables <# comment # Multiline comment Get­Service | Group­Object Status Group services by their Status
Assignment, Logical, Comparison Operators
Scopes global, local, private or script "A `"test`"" Escape char ` dir | Group­Object {$_.Length ­gt 100KB} Group objects bigger/smaller than 100 KB
=,+=,­=,*=,/=,%=,++,­­ Assign one or more values to variable
$global:var = "var" Assign global scoped variable `t Tab Get­Content C:\pcs.txt | Select­String "q­" | sls "win7" Select strings with "q­", "win7" from pcs.txt
­and, ­or, ­xor, ­not, ! Connect expressions / statements
`n New line ps | Format­Table ­Property Name, StartTime ­AutoSize Format ps output showing Name, StartTime 
Arrays ­eq, ­ne Equal, not equal properties, autosize the table
` Line continuation
"a", "b", "c" Array of strings ­gt, ­ge Greater than, greater than or equal ps | Format­table ProcessName, @{ Label = "Total Run Time";  Table showing processname, custom 
­lt, ­le Less than, less than or equal to Expression={(Get­Date) ­ $_.StartTime}} label/expression showing run time.
@() Empty array
Basics of Text and Files Get­EventLog ­Log System | Select ­first 5 | Format­table ­wrap Get first 5 events in system log, wrap display
1,(2,3),4 Array within array ­replace Replacement ­ “Hi” ­replace “H”, “P”
Get­Location Get current directory gi C:\Users | format­list ­property * Get all properties from C:\users in list format
,"hi" Array of one element ­match,­notmatch Regular expression match
Set­Location Change directory "{0}`t{1]`n" ­f $a, 5 ­f operator to construct strings.  {0} replaced 
$arr[5] Sixth element of array ­like,­notlike Wildcard matching
Get­Content Get content of file with $a, {1} with 5 etc.
$arr[2..20] Return elements 3 thru 21 ­contains,­notcontains TRUE if value on right in array on left
Add­Content Append content
$arr[­1] Return last array element ­in, ­notin Reverse of contains,notcontains Common commands PSDrives
Set­Content Set content of file Get­EventLog Get­WinEvent Alias: Aliases in current session
$arr[­3..­1] Display last three elements of array
Out­File Formatted text to file Other Operators Get­CimInstance Get­Date Cert: Certificate store for user
$arr[1,4+6..9] Elements at index positions 1,4, 6 to 9
Out­Null Discard output ­Split Split a string “abcdefghi” ­split “de” Start­Sleep Compare­Object Env: Environment variables
@(Get­Process) Force result to an array
Out­String Convert to strings ­join Joins multiple strings “abc”,”def” ­join “;” Start­Job Get­Credential Function: All functions in current session
$arr[($arr.length­1)..0] Reverse array
Copy­Item Copy items .. Range operator 1..10 | foreach {$_ * 5} Test­Connection New­PSSession HKLM: Hkey Local Machine Hive
$arr[1] += 200 Add to existing array item value
Remove­Item Remove items ­is,-isnot Boolean ­ is object instance of specified .NET type Test­Path Split­Path HKCU: Hkey Current User Hive
$b = $arr[0,1 + 3..6] New array from elements of $arr array
Move­Item Move items ­as Convert input object to specified .NET type Variable: Variables in the current session
$z = $arrA + $arrB Combine two arrays into single array Importing, Exporting and Converting
Rename­Item Rename item ­f Format strings  1..10 | foreach { "{0:N2}" ­f $_ } WSMan: WinRM configuration / credentials
Export­CliXML Import­CliXML
Set­Item Set contents of file [ ] Cast operator. [datetime]$birthday = "1/10/66" AD: Active Directory
Associative Arrays (Hash tables) ConvertTo­XML ConvertTo­HTML
Clear­item Clear contents of file $( ) Subexpression operator Set­location HKLM: HKLM Registry hive
$hash = @{} Create empty hash table Export­CSV Import­CSV
New­Item New empty file or dir @( ) Array subexpression operator gci variable: Variables in current session
@{foo=1; bar='value2'} Create, initialize hash table  ConvertTo­CSV ConvertFrom­CSV
& The call/invocation operator.
[ordered]@{a=1; b=2; c=3} Create ordered dictionary Regular Expressions
Objects
$hash.key1 = 1 Assign 1 to key key1 \w Any word character [a­zA­Z0­9]
Automatic variables
(Get­Date).Date Date property of object from Get­Date
$hash.key1 Return value of key1 $_, $PSItem Current pipeline object \W Any non­word character
Get­Date | Get­Member List properties and methods of object
$hash["key1"] Return value of key1 \s Any whitespace character
$Args Script or function arguments
[DateTime]::Now Static properties referenced with "::"
$hash.GetEnumerator | sort Key Sort hash table by Key $Error Errors from commands \S Any non­whitespace character
"string".ToUpper() Use ToUpper() Method on string
[pscustomobject]@{x=1;z="z"} Create custom object \d \D Any digit or non­digit
$True,$False Boolean value for true,false
[system.Net.Dns]::GetHostByAddress("127.0.0.1") Use static method to get host name with "::"
$null Empty {n} {n,} {n,m} Match n through m instances of a pattern.
$excel = new­object ­com excel.application Create a new Excel COM object to work with
$profile Array of profile locations More Google .NET Regular Expressions

You might also like