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 | whereobject LastWriteTime gt (GetDate).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 | whereobject {$_.path like "C:\windows\system32*" and Processes where path includes system32 and @" HereString quotes, For($i=0; $i lt 10; $i++){ $i } For $var = "string" Assign variable $_.company notlike "Microsoft*"} company doesn't start with Microsoft HereString expressions, etc. Single Foreach($file in dir C:\){$file.Name} Foreach [Type]$var="typedVar" Assign strong typed variable "@ quotes for no expressions ps Explorer | selectobject Property ProcessName ExpandProperty Get explorer processes, select processname, 1..10 | foreach{$_} Foreach Modules | formatlist 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 | SortObject Property WorkingSet | SelectObject 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" | SelectObject Unique Return only unique returns @(a b) Default {Default Statement} $a,$b = $b,$a Flip variables <# comment # Multiline comment GetService | GroupObject Status Group services by their Status Assignment, Logical, Comparison Operators Scopes global, local, private or script "A `"test`"" Escape char ` dir | GroupObject {$_.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 GetContent C:\pcs.txt | SelectString "q" | sls "win7" Select strings with "q", "win7" from pcs.txt and, or, xor, not, ! Connect expressions / statements `n New line ps | FormatTable 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 | Formattable ProcessName, @{ Label = "Total Run Time"; Table showing processname, custom lt, le Less than, less than or equal to Expression={(GetDate) $_.StartTime}} label/expression showing run time. @() Empty array Basics of Text and Files GetEventLog Log System | Select first 5 | Formattable wrap Get first 5 events in system log, wrap display 1,(2,3),4 Array within array replace Replacement “Hi” replace “H”, “P” GetLocation Get current directory gi C:\Users | formatlist property * Get all properties from C:\users in list format ,"hi" Array of one element match,notmatch Regular expression match SetLocation 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 GetContent 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 AddContent Append content $arr[1] Return last array element in, notin Reverse of contains,notcontains Common commands PSDrives SetContent Set content of file GetEventLog GetWinEvent Alias: Aliases in current session $arr[3..1] Display last three elements of array OutFile Formatted text to file Other Operators GetCimInstance GetDate Cert: Certificate store for user $arr[1,4+6..9] Elements at index positions 1,4, 6 to 9 OutNull Discard output Split Split a string “abcdefghi” split “de” StartSleep CompareObject Env: Environment variables @(GetProcess) Force result to an array OutString Convert to strings join Joins multiple strings “abc”,”def” join “;” StartJob GetCredential Function: All functions in current session $arr[($arr.length1)..0] Reverse array CopyItem Copy items .. Range operator 1..10 | foreach {$_ * 5} TestConnection NewPSSession HKLM: Hkey Local Machine Hive $arr[1] += 200 Add to existing array item value RemoveItem Remove items is,-isnot Boolean is object instance of specified .NET type TestPath SplitPath HKCU: Hkey Current User Hive $b = $arr[0,1 + 3..6] New array from elements of $arr array MoveItem 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 RenameItem Rename item f Format strings 1..10 | foreach { "{0:N2}" f $_ } WSMan: WinRM configuration / credentials ExportCliXML ImportCliXML SetItem Set contents of file [ ] Cast operator. [datetime]$birthday = "1/10/66" AD: Active Directory Associative Arrays (Hash tables) ConvertToXML ConvertToHTML Clearitem Clear contents of file $( ) Subexpression operator Setlocation HKLM: HKLM Registry hive $hash = @{} Create empty hash table ExportCSV ImportCSV NewItem New empty file or dir @( ) Array subexpression operator gci variable: Variables in current session @{foo=1; bar='value2'} Create, initialize hash table ConvertToCSV ConvertFromCSV & 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 [azAZ09] Automatic variables (GetDate).Date Date property of object from GetDate $hash.key1 Return value of key1 $_, $PSItem Current pipeline object \W Any nonword character GetDate | GetMember 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 nonwhitespace character "string".ToUpper() Use ToUpper() Method on string [pscustomobject]@{x=1;z="z"} Create custom object \d \D Any digit or nondigit $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 = newobject com excel.application Create a new Excel COM object to work with $profile Array of profile locations More Google .NET Regular Expressions
(The Eddington Memorial Lectures, Cambridge University) Charles Webster-From Paracelsus To Newton - Magic and The Making of Modern Science-Cambridge University Press (1983)