100% found this document useful (1 vote)
3K views

Powershell Cheat Sheet PDF

This document provides a summary of common PowerShell commands and concepts organized into categories including: 1. Strings, flow control, filtering, sorting, grouping and formatting commands and concepts. 2. Variables, data types, scopes, comments, escape characters and arrays. 3. Operators for assignment, logical comparisons, regular expressions and more. 4. Basics for working with text files and formatting output. 5. A list of common PowerShell commands.

Uploaded by

zC6MuNiW
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
3K views

Powershell Cheat Sheet PDF

This document provides a summary of common PowerShell commands and concepts organized into categories including: 1. Strings, flow control, filtering, sorting, grouping and formatting commands and concepts. 2. Variables, data types, scopes, comments, escape characters and arrays. 3. Operators for assignment, logical comparisons, regular expressions and more. 4. Basics for working with text files and formatting output. 5. A list of common PowerShell commands.

Uploaded by

zC6MuNiW
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Strings Flow Control Filter, Sort, Group and Format (aliasesforbrevity)

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

You might also like