100% нашли этот документ полезным (2 голоса)
7K просмотров1 страница

PowerShell Operators and Arrays Guide

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.

Загружено:

zC6MuNiW
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
100% нашли этот документ полезным (2 голоса)
7K просмотров1 страница

PowerShell Operators and Arrays Guide

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.

Загружено:

zC6MuNiW
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
  • PowerShell Cheat Sheet

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,[Link]
Foreach($fileindirC:\){$[Link]} 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:\[Link]|SelectString"q"|sls"win7" Selectstringswith"q","win7"[Link]
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 [Link] TestPath SplitPath HKCU: HkeyCurrentUserHive
$b=$arr[0,1+3..6] Newarrayfromelementsof$arrarray
MoveItem Moveitems as [Link] 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"::"
$[Link]|sortKey SorthashtablebyKey $Error Errorsfromcommands \S Anynonwhitespacecharacter
"string".ToUpper() UseToUpper()Methodonstring
[pscustomobject]@{x=1;z="z"} Createcustomobject \d\D Anydigitornondigit
$True,$False Booleanvaluefortrue,false
[[Link]]::GetHostByAddress("[Link]") Usestaticmethodtogethostnamewith"::"
$null Empty {n}{n,}{n,m} Matchnthroughminstancesofapattern.
$excel=[Link] CreateanewExcelCOMobjecttoworkwith
$profile Arrayofprofilelocations More [Link]

Other Operators
­Split
Split a string “abcdefghi” ­split “de”
­join
Joins multiple strings “abc”,”def” ­join “;”
..
Range ope

Вам также может понравиться