0 ratings 0% found this document useful (0 votes) 10 views 55 pages window full powershell cheat sheet
The document is a PowerShell cheatsheet designed for beginners, outlining the features, advantages, and historical context of PowerShell as a command-line shell for system administrators. It covers various versions of PowerShell, command structures, and the importance of execution policies, along with examples of basic commands and how to access help. Additionally, it highlights the integration of PowerShell with the .NET framework and its compatibility with other Microsoft languages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save window full powershell cheat sheet For Later rss / ronal a\(e)
© Code © Issues 1 T1 Pullrequests © Actions ff Projects © Security Let Insights
oly a
PowerShell Cheatsheet
Sr MSs Y 25 leks © Wwatching P Bancres 4 Aatviy
© ss
© Poste repostony
¥ vane +) ¥ teanch Oot FO @ Gotote ©) Gotosie | Addtie +) cove
B sergsin Usene saticd syasaoe ©
D ReADMEme Ups README a years age
»
PowerShell
PowerShell Cheatsheet
PowerShell for beginners
‘This document Se getting updated tine-to-tine, Become a watcher to get updates:
PowerSell isa windows command-line shell designed especially for system administrators las bult on top ofthe NET Framework common
language runtime (CLR) and the NET Framework So, t accepts and returns NET Framework object
PowerShell works in both INTERACTIVE mode and SCRIPT mode. I possesses emdlet (oronounced ‘commande fer doing pre-defined tasks
1. Why Should | Learn Another Language?
Tere wont be much gan without any pai, | would recommend leering powershell ecase ofthe advantages that offers
Advantages
1 Easein accessing fle systems
‘Abily 10 access other data stores, suchas regis and agit signature ceria stores
‘Open-source and increasing communty base
‘Apart from windows, itis extending support fo Linux from next release
‘+ As PowerShallistghty coupled with NET framework So, NET objects can be used
‘+ Ease in working with all Microsoft products (Office suite Client OS, Server OS, lS, Databases, Visual Studio Suite, ete)
‘Abily 0 conneettoeastng windows administrative functionaiy
= wm
“+ Microsoft NET framework
‘+ COM (Component Object Model
‘+ ADSI Aative Directory Services Interface)
‘+ Can be used to automate almost any administrative task2. About PowerShell
2:1 PowerShell History
Intally, when windows was launched forte fist ime, came with the MS-DOS, Later, in 1981, batch script (CMO) was introduce followed by
[VBScript in 1996 and PowerShell in 2006, PowerShell script hove pst as the fle extension. Here, the "Tin “ps1 does refer to the posverShall
version: rather refers tothe version ofthe engine, which uns the powerShell
2.2 PowerShell Versions
PowerShell 10
“+ Installed but not enabled on windows Vieta and Server 2008
PowerShell 2.0
+ stalled by default on Windows 7 and Server 2008 R2
‘+The PowerShell SEs installed by defoult on Windows 7
‘+ Cane installed on Windows XP and Server 2008 or Higher
PowerShell 3.0
«+ Installed by default on Windows 8 and Server 2012
‘SEs installed by default on Windows 8 and Server 2012 GUI
‘+ Canbe installed on Windows 7 and Server 2008 or Higher
‘+ PowerShell Remoting is enabled by default on Server 2012,
‘There exist some cifferences between these versions, and the atest version of PowerShell is 6.0. The suitable PowerShell version for windows
PowerShellVersion Release Date __Default Windows Versions Available Windows Versions
PowerShell 19 November 2006 Windows Server 2008 (*) Windows XP SP2
Windows x SP3,
Windows Serve 2003 SP1
Windows Server 2008 SP2
Windows Server 2008 R2
Windows Vista
Windows Vist $2
PowerShell20 October 2008 Windows 7
Windows Server 2008 82 (**) Windows XP SPS,
Windows Server 2008 SP2
Windows Vista SP1
Windows Vista s2
Windows Server 2008 $P1
Windows Server 2008 SP2
PowerShell30 September 2012 Windows 8
Windows Server 2012 Windows 7 SP1
Windows Server 2008 SP2
Windows Server 2008 R2 SP1
PowerShell 40 October 2012 Windows 1
|PowerShell Version Release Date Default Windows Versions ‘Avilable Windows Versions
Windows Server 2012 R2 Windows 7 SP1
Windows Server 2008 R2 SP1
Windows Server 2012
PowerShell 50 February 2016 Windows 10 Windows 8.1
Windows Server 2012 R2
Go to windows menu, and type Windows Powershell (don't choose Windows Powershell ISE ) and open it
2.3 PowerShell Environment
To get the PowerShell version installed on the machine, ype
PS Cx» ssverstontable
Psconpatibleversions 2,8, 3.8) 4.8.04)
autleversion 130.0. 10586.67:
PstenotingPratacolversion 2.3,
Sertalizationversion aed
(Observe thatthe esversion which is $.0 inthis case.
Toget the Host detail,
95 CH\> Got-nest
None consolevost
Currentculture en-US
Correnturcalture + en-us
Drivatepata + Hicrosoft,Pouersnell consolevostsconsoleColorProxy
stunspacetushed + False
unspace System. Managenent.Autonstion.Runspaces.Lecelunspace
senv is a predefined variable in powershell. twill store the complete windows environment information
Printing itbarely doesn’t result in any information.
PS C213 fenv
ps cae
‘The senv variable must be accompanied by the other coresponding variable,
5 c:\> Senv:CowPuTERNAne
PS C2\> SenvsuseANaME
PS C2\> SenvUSERDNSDORAIN
prakach.con
95 c:\> SenvsusenPROFZLE
cHusers\uoHay
»1S C2\> SenvsALLUSeRSPROFILE
:\progeanbate
95 c2\> Senviconspec
{\windows\systensa\end. exe
PS C21» Senvssomepath
\sers\umiay
95 C2\> Senvinoweonrve
PS C2\> SenviPrograntsles
C\progeam Files
NOTE: Ifyou dont know sll the variable part of i after = type tab key toall those variables one-by-one,
2.4 Support for Other Microsoft languages
PowerShell used concept called alsases to support commonly used commands in other Micrasoft languages like Batch Script (CMD), VSript,
et
‘Commonly used Batch Script CMD} commands such asd cls. are supported in PowerShell
PS C21) Chearstost # sate as cls In CHO; clears the seneen o
But they doesn’t support those commands extensively. For example, gir will work: butnot dir 0
‘To explicty run the commands andr scripts of other language in powershel
Sconnand = @ e
endvene /C dir [4:0
e
Tnvoke-Expression -Command:Sconnand
But le’ ignore this until we understood ths language syntax and semantics,
2.5 Command Structure in PowerShell
PowerSnell possesses light-weight commands, called cmdlets, to do some specific tasks,
‘They usea consistent verb-noun structure where the verb represents the ation and the noun represents the object to operate on.
PPowerSnell emelets follow consistent naming pater, ensuring that construction ofa commandis easy ifyou know the object that you want to
work with
All command categorie take parameters and arguments. parameter starts with a hyphen ands used to contrl the behavior ofthe command,
{An arguments data value consumed by the command.
Asimple PowerShell command has the flowing syatax
‘comand -pararetert -paraveter? argent, argument2 o
Togetthelstof approved verbs ,
PS c:\> Get-verd e
»eat oman
ige common
oven oman
[Taltored the 1st]
‘The Groupings done based on their common use
ach Windows PowerShell verb i assigned to one ofthe fllowing groups.
‘+ Connon : Define generic actions that can apply to almost any emelet such as Ade
‘+ conrunteattons : Define actions that apply to communications, such as Connect
+ bata : Define actions that apply to data handling such as Backup.
+ otagnostic : Define actions that apaly to diagnostics, such as Debus,
‘+ Lifecycle : Define actions that apply to thelfeycle ofa emt, such as Complete
‘+ secuntty Define actions that apply to security such as Revoke.
+ other : Define other types of actions
‘Toget thelist of all nouns
9S C2\> Got-Command Noun * e
comanatype Mane nodulevane
Function Disable-Pstrace Psoingnostics
Function Disable-PsuanconbineeTrace Psbiagrosties
Function Dusable-Ksmantrace Psoiagnostics
Function Enable-estrace Psptagnostics
Fonction Fraple-PsuStanconbinedtrace Pspiagrostics
Function ‘cet-Dseconfiguration Psbesiredstatecontiguration
Function ‘Get-DscLocalContigurattontanager Psbesireastatecontiguration
Function ‘cet-bscresource Psvesiresstatecontiguration
Function ‘oet-Fslesash ierosof® Powershell Utility
Funetion ‘set-tsesrippet se
[Tatiored tne list]
(Observe that Get-ver® toais amour,
Also, theres another command named Get-comnand to get particular set of commands
‘To getall the command in the current user scope in a particular windows machine,
PS C219 Got-Command AIL e
comaratype Mane Nodutevone
alias cat => Ges-content
muse a) set-Loeaeion
muse clear => Clear-tost
niae aby => Clear-tistory
nuiae history > Set-tistory
»aus sein => csncraiets
Function ‘oet-tneSnippet 186
Fanetion Pspisgrostics
Function Trvoke-Assorkou Pskorkslowtsisy
Function new-Tse5nippet se
cnauet Set-tppLockerPolicy optecker
crater set-cininstance cincraiets
cadet set-sxecutionPolicy icrosoft. Powershell Security
caster Sset-obrrigeer Psscheauleadon
cnalet set-teolAdninssteativeunit nsonlinetitendes
cxatet Start-osccont guration Psvestreestateconttguration
crater ieste-everttog icrosoft.Powarshell.Managenent
caalet este-tiost Nicrosoft Powershell ULILity
[Tattered the 1st]
‘Also, the commands can be retrieved in terms of nave , Verb , Noun, Mocule
PowerShell also possesses 2 strong and unique feature called piping , which wecan discuss under the piping section
2.6 Getting Help in PowerShell
‘Once the command to works known using Get-Connand , the Usage and syntax ofthat particular emdetcan be learned using Get-e1p
Toget the help for a particular cmt say elear-Host ,
PS C219 Get-Help Mane elaar-Host e
Clear-host []
The Clear-vost function renoves all text from the current splay, including commands and output that aight have
Ctaplays the command prompt. You can use the function nane or Sts alias, Cis
Clearchast affects only the current atsplay. 1% doce not
Session. Sesstor-specitic tens, such
2s variables and functions, are not affected by this function.
because the behavior of the ClearcHost function is determines by the host program, Clear-host might work
‘online version: http: //technet nicrosort.con/1tbrary/nna5s2689(sewps.630) 259%
Tp se0 the exanples, type: “get-nelp Clear-tost -exanglies
For nore information, type: “get-help Clear-ost -dctailee”
»For technical inforeation, type: "get-help Clear-Host full”
For online help, type: "get-help Clear-Host online”
(Observe the 6 fields (nane,, synopsis , syntax, Deseeistion, Related Links , Renarks J These are common for allthe results of get-tele
Itusage by exampleis needed,
PS C11» Got-Help Mane clear-Host Examples o
smorsis
Clears the éisplay in the host progran.
capseas
PS Co\nGet-Process
Handles NPMCK) —PRCK) ——_HS(K) VHEM) CPUS) Td Processnane
ra 3k aaah 20.22 4009 ears
76 7 aah S68 Sk 8.81028 can
382227602, 45980 910,23. 3056 LogonUr
wen 212204325 5.07 Sab Tease
4473 Tenn 84476 201 1,429.67 436 HSHpEne
2X6 Ga78— 40775031582 Mies
dod 25M? SSOR 6I4 «1.78848 powershell
sel 8 -23e Gaze 70 Gk 3648 rupee,
Ps cc\y als
‘his conmane uses the CLS alias of Clear-Host to clear the current sisplay:
To update the help (ensure proper internet connect, as it downloads from PowerShell site)
PS C21» Update-Help e
psc
2.7 Importance of Execution Policy
By default the execution Policy is setto’Restricte! is recommended to change't to Restore Signed
»Execution Policy Ws importance
Resticted ‘Yu can run commands, but yeu can run septs
All Signed You can run commands, but you can only un digital signed serps
Remote Signee You an rin commands, local septs an only script downloade fom te internat if they ar itl signed
nested You an ra command and scrips with or witout cit signatures
Bypass Nothing is blacked and tare are no warnings or prompts
In windows menu, type windows Powershell , rightclick on itand cick Run as Adninistrator Then type the below command tothe
ExecutionPoliey on that machine fr that user.
5 CoA» Got-txacutionPolicy o
By default twill give the exection policy associated with the user who executed this command,
PS C2\> Got-txacutionPolicy -Scope currentUser e
Also, replace the Currantuser inthe above command witha specific username on that machine, to know the execution policy associated with
that user,
ToCChange the execution policy to say unrestricted,
2S C:\> Set-ExecutionPolicy -ExecutionPoLicy “unrestricted” -Scope Currentuser e
execution Policy Change
‘he execution policy helps protect you from scripts that you ¢o not trust. changing the execution policy might expose
hetps//go-nserorotcon/fwlink/?tSnk19~135178. 09 you want s9 change the execution policy?
[vi vee [IM] No [8] suspend [?] lelp (default is "¥"): ¥
Ps
3. Working with PowerShell
3.1 Getting Started
A itis customary to star with “Hell world" when learning any language, Lets start with it
9S C2\> wedtesiost “Helle Mort!” e
Nelle wort!
95 cr\> krstestoet “Hello Morte!”
hetle woridi
PS C213 “Helle Morte”
‘Observe that the string ‘Hello Worl is printed onthe console in three ways. But single () andl doublet’) quotes won't work exactly same in all
cases, we can discuss aboutitin later section,
Single-ine comment
PS C:\> # Conants begin with 2 # (aka hashtag or pound sen) o
ps cs
‘Multiline comment
»psc o
95 Connent blocks use angle brackess with comment sian
>> They can be multiline
esc
Regions are notlogical but representational blocks of code.
NOTE: Regions have their importance in powershell SE only. They are used to divide the script into logical code blocks.
2S c2\> region o
PSC: # Put your code here
95 C:\> endregson
ps cnt
‘Tes regions can also be named,
95 :\> tregion The Region Title 4s optional o
ps crs
9S C:\> # sone code here
ps cy
PS C:\> endregion The Region Title 1s optional
ps cy
‘Special characters in PowerShell
Special
ann Meaning
. The beginningt or end) of quoted text. Used to represent strings
‘The beginning or end) of quoted text, Used to represent strings, special characters lse tei significance within single
quotes
* The beginning of comment
‘ The begining of a variable
a Reserved for future use
0 Parentheses used fr subexpressions
0 Scriptblock
5 Statement Separator
Pipeline seperator
Escape Character
2 ‘Alias operator fo: Where-Object
* Alla Operator for for-toop
All variables start witha.
9S C:\> hi = "Hello Morid” o
Printing the value invariable
Ps c:\> shi o
This isa shortcut to Write-Host
»Ps ci\> Keste-tos
bello word
Variables are objects, and to get their datatype,
Ps cre snt.cert
st shi
ype)
saserype
Systen. object
Gettype0 is one method, applicable on ‘Sh object
‘To display all the members of ths variable (objec)
PS cH\> ht | cet
Henbertype
Clore. ethos
copyto Method
Endsuith tethod
Equals (steing
Getérunerator Method
Getinehode Method
Gettypecode Method
radon,
indexorany Method
normaliz--.
astinaeso! method
ine
normalszat.
Paatere ethod
paedingcnar)
asnight Method
padding.
feplace ethod
split sethod
system, stesnaton.
substring Vrethos
Tobsotesn ethod
Tocnarseray Method
oonterine method
Jooecinal ethod
Tooovble ethod
systen.ooject Clone(), systen.coject 1Cloneable.clone()
int Conpareto(syster.Object value), nt Conparefo(string strb), int
boot Contatns(steing valve)
void CopyTotint sourcetnaex, chart] destination, int destinationtndex, int
bool Endsith(string value), bool Endswith(string value,
boot Equals(systen.cbject obj), bool Equals(string value), boot
systen.charErunerator Getenunerator(), System, Collections, TEnunerator
ne Gatharncoae()
type Gettyee()
systen.TypeCode GettTypeCode(), Systen.TypeCode KConvertible.GettTypecode()
nt IndexoF(chor value), int IndexOF{char value, snt startrncex), 498
nt indexorany(chart] aryOF), int Indexothay(char{] anyor, ant startingex),
string Intere(int atartindes, string value)
boot TsNarmalized(), bool rsMlormalized(Systen.Text.Noomalizationtorn
fant LastindexoF{enar valve), int LastindexoF(char value, int starttndex),
Ane Lastindesorany(cnar{] anyof), int Lastindexortnytenar] anyor, tnt
string Mormalise(), string Noraalize(Systen. Text Morsalizatsonform
string PadLert(int totaliigth), string Padlefe(int totaluieth, char
string PadRight(iat totaiNtdth), airing PadRight(int totaluieth, char
string Rerave(int startindex, int count), string RenoveCint startindex)
string Replace(char olechar, car newchar), string Reglace(string eldvalue,
stringl] Split(Psrans char] separator), string[] Split(ehart] separator,
boot startswltn(string value), bool startswttn(string value,
string Substring(int startindsx), sting Swvetring(int startingex, toe Length)
boot Icanversible. ToR0olean(Systen,IFornatrovier provider)
byte Iconertibie. Tedyte(syster.IormatProvider provider)
char icanvertible.Tochar(Syster.IformatProvider provider)
char] Techarseray(), char[] Tacharaeray(int startindex, Let Lengtn)
catetine Iconvertible.Tobaterane(systen.ifornatProvider provider)
ecinal Icorvertible, TeDecinal(systen, ForeatProvider grevicer)
souble IConvertsble.1odouble(Systen.IFornat?rovicer proviger)
»rotrtas ethod Antas convertible. Toont26(Systen LFornatProviser proviger)
qemrtse othe Int {convertible toint32(systen,tForeatProvider provider)
Tomes othe Ione tconversibie-totavea(spsten,trornatproviger proviger)
Telos ethed fining ToLover(), string Totower(euitureino culture)
Tetowerznvartant Method ining Toloverdmvariane()
Tosnyte eth byte. 1eorvertible.Tostyte(systen. 1Forntorovider proviger)
Tesingle ethos ‘oat icorertible.esinele(syeten.troreatoroviger provider)
Tosering ——tathed fring Testring()y sering Tosteing(systonTrernatrovider provider), string
saiype sethod syten.onject Iconvertible.Totype(type comversiontype,
Joutreie. method vint16 Iconvertible, Tovtret6(systenIFomattroviaer proviéer)
Toutntse Method ints2 Keonertible.Yoviresa(syetentrorateroviger proviger)
Touintes tho vintes Iconvertible,Tovtreed(aystenTForattroviger provider)
Tupper sethed fining Tedper(), string Tolpper(cuitureino ulture)
Teuppertnvartant ethod Hering Topperimvariane()
trie ethed Eiving Tein(oarane char{] teincnars), sting Tein)
Tinend eth String Tinendfprans chart] trinchars)
Teiestart athe ining Teinstart(Parans char{] telachars)
cere Dareneterizedpropersy chor tharsCine inde) feet)
Length froperty ine vengeh (eet)
Using some of those members
#5 C29 Sat ToLovert e
5 cs\> Sat Taupe)
PS C:\> SmiLength # No (a8 48 46 Property: not nethod
a
95 cs\9 Shl-Aeplace( orld", “PowerShel1*)
“Types ae mutable Thelr data types cn also be changed
o
Ps cts nt
PS Coy shi. cettype(
IsPublic rsserial Wane saserype
in Syrten.valuetype
PS Co\> ht | cetMender
Nore enberType Definition
CowpareTo wethoe int Conparero(systen.Object value), tnt CompareTo(int valve), int
cowparable.Conpareto(Systen.0bj.-
Equals Wathoe bool Equals(systen.0bject obj), bool Equalstint 063), bool Tequatable[ int] -EcualsCint other)
GesiashCode Hethod ne Gettoshcade()
Gettype Method type GetType()
GetTypecade Method Systen. TypeCode GetTypeCade(), Systen.TypeCade IConvertible.GetTypeCode()
Toscolean ethos bool TConvertible,Tosoolean(syster.1FornatProvider provider)
Tobyte Method syte IConvertible. Tonyte(Systen.ttaraatProvider provicer)
ochar ethos nar Tconvertible.ToCnar(systen.2FormatProvider provider)
Tebatetine Rethed datetine. Iconvertible. TobateTine(Systen,FarmatPravider provider)
Tooecinal Method dacinal IConvertible.Tobecina2(Systen.IFornstProvider provider)
Teosuble Methow double TConvertible.Tobauble(Systen-IformatProvider provider)
Tomes —_Nethog _int16 TConversible, Toxnt6(systen.IrornatProvider provider)
omnes? int Teonvertibie.roints2(Systen.FormatProvider provider)
eines ong IConvertibie. Tolatse(systen.tfermatProvider provider)
restyte ayte IConversibte, Tostyte(Systen-IformatProvider provider)
»Tosingle Methos lost KConvertsble.Tosingle(Systen.1FormatProvider proviser)
osering nethog string ToString(), string ToString(string format), string Tostrine(Systen,1Fornaterovicer
proviser
Totype Method Systen.object Iconvertitle.ToType(type conversionlype, systen.IFormatProvider provider)
Toutrtss method int 6 EConvertdble, ToUIntd6(systen.TFornatProvider: provider)
yourrt32 Wetho# —int32 Xconvers ible. ToUINe72 (Syston. TForeatProviger provider)
Fount Method int6a_ZConvert ible. ToUIntEa(Systen,TForeatProviger provider)
Variables can also be strongly-typed.
9S Coy [system tntszlgayint = «2
2S CA» Saysne
PS CH» saying GetrType0)
BS CoV» Saying = “THSe won't wore”
+ categorytnto Metadatatrror: (:) (J, AngunentTransfornationkatadatatxception
| FullyQunlstiettrrorts + Runtinetxeeptson
‘There are shortcuts for most NET data types.
PS c:\> [int] Sayotherint = 42
PS C:\> Sayotnerint.cettType()
ePublic IsSerial Mane
95 C:\> [string] Snysteinge*Poversnel?
Ps Cx» mystrtng.settype()
‘others include shor float, decimal, single, bool, byt, ete
"Not ust variables have types - so do static values
9S C:\> “Powershelt Rocks" Gettypet)
republic IsSersal Mane
‘Accessing methods on objects
PS C:\> “Powersheli Rocks" ToUpper()
psc
roerShel Rocks". Contains(“Powershell")
For non-stings you need to weap in $0 PS will evaluate as an abject.
e
saserype
systen.valuetyoe
e
aaserype
aasetype
Syston. object
o
baserype
o
IPS Ci\> (33).GetTypet) e
IsPublic IsSerial Wane saserype
Logical Operations
operator Importance
“4 Equalto
ne Not equal to
a Less Than
oe Greater then
ae Less than or equal to
* Greater then or equal to
| 4 | See f value in an aray||-Like| Like wildeard pattern matching] | -NotLike | Not Like | -Match | Matches based on regular expressins| | -
[NotMatch | Non-Matcnes based on regular expressions]
PS Ci\> Svar = 33 8
95 c:\> Svar ge 38
Ps cx\s Sear Ie 30
95 c:\> $uar -e0 33
Calculations are ike any other language.
PS. ci\> fuar = 3 F 11 # Also Uses +, -) and / e
es co» ear
‘Supports post unary operators ++ and
Ps c:\> fares o
ps cots far
‘And pre unary operators as well
95 ci\> ea$var o
ps cre fear
PS C23 fear = a0
PS C:\> post = svanse
PS C:\> wrdtestont Spost, Svar
psc
»ps c1\> var = 33
PS C219 fore = veuar
9S i\> wrdtertost Sore, Svar
Be cautious of Implicit Type Conversions
9s crs "a2" 00 2
2S C23 a2 weg “ae
‘whatever ison the rights converted tothe datatype onthe lft can lead to some odd conversions
PS C:\> 42 eq "B42" true because the string on the right fs coverted to an Sat
ps cry
False.
Built in variables
PS C219 # aaoleans ( False and trae)
9s cre false
False
PS coy steve
PS c:\> SWILL # rudd type
PS CH» wrdcestont Shull
‘Observe that nothings spay; even methods like GetTypot) doesnt work an this object.
To getshe current working directory,
Ps cA» sd
‘To get the Users Home Directory,
PS C219 $home
\Urers\praudet
Information about a uses scripting environment
PS C:\> $host WIL 4s alas for Get-Host
nore Mindows Powersnel TSE Host
Instancer sei fea3-4255-4095-9299-109¢91864c8?
ur ‘system. Managenent.Avtonation. Internal lost. IntemnalhostUserinterface
Currentculture en-us
Currenturcalture + en-us
privatenata bierosoftPouershel Host. 196. 1SEOptions
»Debuggerenabled + True
unspace + Syston.sanagenentutonstion.unspaces.LocalRunspace
psc
9s C:\> $ID Tt results the process 10
Info about the current version of Powershell
2S CoA» ssverstonrabte
psversion
Dsconpat sbleverstons >
lstarstaceverston ae
PstenotingProtocolversion 2.3
PS CH) $_ Current Ooject: Used tn Loops to get the iterating object,
PS C:\> # Useful, mainly, in Loops and exceptions
2S C2\> Set-Location “C:\pythonz7\Serspts*
1s cr\Pythona\seripts> # set-Location works An the sane way a chair
PS Cx\Pythona7\Seripts> Get-Chilerten | where-Object ($_Nane -Like “*.ene")
Directory: c:\Python27\scripts
tara? 789 ak 1632 weed
@hmar17 265 Ak 24 nyson.cnd
pactanca? $259 PH 351 wnitert.end
Ps cr\Pythona7\scripts> set-location ¢:\
ps cs
Using the *-Varable emdlets
95 C1\> # Nona vardable usage
PS C2\> Sorel = 33
95 C2\> Srommat
PS C21» $text = "In The Horning
PS c2\> stext
In The Horning
PS C19 # Long version of Svant = 33
2S C:\> New-vardable -Nawe vert -Value 33
»Ps crs fant
»
NOTE: H you try to se New-Variabl and it already est, you get an error.
Try again with $var1 already existing
95 C:\> New-variable -Nave vart Value 99
Newevarsable + A variable with nore "vars" already exists
+ categoryinto Resourcetxtsts: (vart:String) (New-Vardable], Sessionstateexception
+ Funlygualstiegtrrortd + vardaplealreseyexists,sscrasofe, Powershell Comands.New/srsableconmane
2s C29 fear
PS C:\> # Displays the variable and it" value
PS C2\> Got-vardabie var -valueonty
9S C:\> Get-vardable var
PS C:\> Got-vardable without parans {f shows all variables
. Gor-varisbie
bow parapomnr_sounce public class ADK OATAPOINT_CLASS ¢
ane oO
dre_easte arate st name, applicationNane, backencvane, conponents.-.}
‘ATC00_NOT_PVBLISH_ATTRIB_LIST (nave, applicationvane, backenaVane, components...)
‘ngsLAPA_XMT_FILE \befaulevalues. x0]
‘nas_otobAL Van FILE \aksclopalvarsaples. pst
ote systen. Windows Forms button, Text
CuoReSTATION_JAR_ PATH \cluerkatation sar
conrts cLass_S0unce pubite lass COWFTG.CLASS (
conftrapreference wan
(ALAR, SOURCE public clase CH ALARH_CLASS (
ceMeraze_ source public clase CKMETRIE CLASS {
Debugprererence Silentlycontinue
2_ELASS_ SOURCE pubic class C2 CLAss (.
error (A vartable with'nsne "wari" sleeady extsts., A variable with mane "var" alreaey
Executioncontext system. Managenant.Avtonation, Enginezntrdnsics
fase False
foreach
owe \Users\praudot
ors system. Managenont.Autonation. Internal Host ntemalost
: 2
input system. Coldections.ArrayListsArrayListenureratorsinale
nachos (o)
Raxinuntlsascount 1996
naxinunprsvecourt 4998
»axinuarunctioncount
naxtnunisstoryCount
axinumarsaplecount
yTavocation
syothenint
systring
utputenceding
Playlisturt
provile
stoundaranesers
psculture
stent Iserver
Psseriptteat
Pssessiondpolicationtane
Dsseresoncontigurat ontane
ssessionoytion
psunsupportedconsotespplica
psversionTable
spetita
inasttPrererence
‘system. managenent.Avtonation. Tnvocationtnfo
Powershell
system. Text. s8cScodePagatncoding
eto: / umn. youtube. con
:\Users\prauden\Docunents\incousPowershell Microsoft PowershelLISE_pro¢4epet
oO
oO
:\Windows\systens2 \indowsPowershel\v1.8
Hicrouoft, Powershell. Host. 156 ObjectModel Root
hta:/schonas.nicrosort.con/povershell /Microsoft Powershell
System. Managenont.Actonation.Renoting.PSSerssonoption
{orte, wntevene, end, end-enes.-}
(Psversion, PsConpatibleversions, BuildVersion, Claversion
icrosofs-Powerstel
Gt calisite.larget(Closure , calisite , object )
system. _Condbject
In The Morning
(eCinnerTexte9:53; uRLanttp://i. youtube con/watch?ve6VKATIGURER}
{@(LonerText=5:08; URL=htts:/ mu youtube,con/wateh?v=cpLURNej9XQ}, @{EnnerText
continue
False
Assigning a new value toan existing variable
Method 1
PS C2\y Suan = "In the Horning e
‘Method 2:
PS C2\> Set-Vardable -Nawe vant -Value “In the Horning! e
Ps c:\> Svar
PS C2\> Set-Vardable -Nane var89 Value “In the Morning’
‘Observe that set-variable works on objects that arent created yet
To dear the contents ofa variable,
»PS C:\> Clear-variable -Nane vari ¥ Sane a5 $vart
Ps cx» fant
ese
Tosetthe variable to null object,
Ps c:\> Sart -e9 Snull
ven though the object contains ull it sil exists.
PS C29 Got-vardabie var
nove. vale
4. Working with Strings
String Quoting
PS Coy “Inks ts a sted
2S CH\> “Tnis 45 2 steing toot
nis 1s a string too!
Mixed quoted
9 c:\> ‘2 Just wanted to s8y “Welle World", 04?
1 just wanted to say “Hello world", 0K?
PS C:\> “T can't belSeve how cool Powershel] Ss!"
You can also double quote to get quotes in sings
95 C:\> “T sust wanted to say “*Helle Worte”*, of”
1 just wanted to say "ello world, 0X?
PS C2\y “d ean'"e believe how cool Powershell is!
1 ean't believe how cool Posershell Ast
Escape Sequences - use the bacitck”
backspace ‘b (does not work in SE only the regular script window)
PS C2\> “Power” bshetl”
95 c:\> "Power" nshet”
Srett
carriage return (doesn't really show anything)
S
S
»95 C:\> "Power" rshetl” o
Shell
cite
5 C:\> Power’ r° nse” e
tabs
95 C:\> “Power sshell” e
Power shell
Replaceis cave-renstve
PS C2\> “Holle worid’ Replace(o", “1°) e
Replace is case-nsentve
PS C:\> “Welle wordd’ -Replace ‘o', ‘1! e
heuis varia
But werneed tobe careful when working with special characters.
5 C2\> “Hols world. ".Replaee(".*, *2°) 4 Replaces only the dot(.) character e
ete world
PS C:\> “Melle wortd.* Replace *.', *2 ‘Replaced the complete string. Assumes *." as regex
ps ci
PS C:\> “Holle world.” -eplace [Regex] ::Esc3pe("
PS C:\> “Melle wordd.* -eplace “\.t) *2 ‘Regex characters con also be escaped with *\
Netie woruds
75 C:\> “Hello worid\’ Replace “\\', ‘1 4°\" enaracter wil oe escaped wisn another
hetle world
ere Steings are used when working with arge blocks of text,
PS C21» heretexe = 8° e
a)
2S C2\> Sheretent
Ppt nore
‘The @ and quote must be last on starting line then first on ending ing, also works with single quotes.
95 C:\> Saoreneretent
>> Here we go again
5 another line here
35" net's indent this
»>> a blank Line above
ner)
"Note how the nested "is handled OK no double quating needed
PS CX» Sareners
Nere we go again
‘another Line nere
let's sndent thie
‘To understand the importance of here strings, lets work with a mulipleline string,
Without here stings
PS CHA» fegl = "SELECT colt”
dsb WHERE cold = "a valve’
psc
Ps co» $sqt
With here strings
Ps c:\> $sql = @
b> seLeer colt
oy col
De
ps cr» fra
Rom sonerable
WERE coll = ‘2 value’
String Interpolation
2S C:\> Set-Location C:\eythonz7\Sentpts\
‘hee the output of Get-Chileltem, which isan object and gets that objects count propery.
95 ci\pythona7\seripts> sitens = (et-chilerten) Count
Ps CH\python27\Seripte> Sitens
“ke the output of Get-Location and store tin a variable
2S cs\Python27\sertpts> Sloe = Get-Location
95 c:\pythona7\seripts> Soe
python? \Sertpts
Use these variables ina string
»Ps c:\Pythona7\scripts> “There are Sitens Stens are in the foleer $106."
‘there ane 287 trons are in the folder €:\pythona7\serspte
To actually cisplay the variable escape it with a bactick,
1s ci\pythona7\seripts> “There are “Sitens stems ane tn the foleer “Sloe
There are $item ftens are in the folder Sloe
String interpolation only works with double quotes
95 c:\Pythona7\Sceipts> “There are Sitens Stens are in the folser floc
‘ere ane $itens iene are in the folder $loe
Siting Interpolation works with here strings
Ps c:\python27\seripts> shereinterpolation
9 Ttene tolaer
>> Stems teste
a
P5 c:\Python27\scripts> shereinterpolation
Enpythonan\serdpts
Ps c:\python27\seripts> shereinterpolation
> Stems’ e'esiee
95 cr\Pythona7\seripts>
9S CA\Python27\Seripts> Shereinterpolation
Sitens't t$loc
‘Observe that it ich’ work for here strings defined with single quotes,
expressions used within sings, need to be wrapped in $0.
95 cr\Pythona7\scripts> “There are $((Get-Childtten).count) itens are in the Folder (Get-Location).”
‘inere ave 287 itens are in the folder C:\Pythona7\Serspts.
2S C:\Python27\Serspts> “Tosay $s $(Get-Dete). Be well.”
Today $5 05/03/2037 12:49:17. be well
bs cr\pythona7\seripts> "the 5K tip of 9 39.33 dolar bil 4s £(33.33 * 6.5) dollars*
‘he 85% tip 9f 9.33.33 dollar sll 19 4.9995 dollars
String Formatting -C# lke syntax supported In C# you'd use:
2S Co\python27\seripts> [string]::Farmat (“There are (8) stens.", $itens)
Powershell shorteut
Ps c:\Pythona7\serdpts> "There are {8} iene.” -# $itens
‘inere ae 287 ivens.
PS cs\Pythona7\serspts> “There are {@} Lens in the Location {1}.° -# Sites, flee
»‘are ave 207 itens in the Location c:\Python27\seripts.
Ps c:\pythona7\seripts> "there
are {@) itens in the Tocation (1). How, (8) 45 2 lot of Stans! -F fitens, Sloe
There are 287 Lens in the Location C:\python2/\Serspts. wow, 287 is 4 lot of Stems!
Pre-defined formats
N= Numbers
+c -Currency
+P -Percentage
2 X-Hox
+ D-Decimal
(0 {@:N0} formattou -# 12345676.229 o
95 c:\> “Wl {82N2} formatteu” -F 12345678.2129,
112,345,578. fonmatted
95 ci\> "ha {ND} formattes” -f 12345678.129
95 C:\> "No {82ND} formatted” -# 123.139
Ne 123 fornatces
PS C2\> “RO {@,8:NO) formatted” - 129.238
Ne 123 fornattea
c= cumrency
2S C2\> “C0 {8:C0} formattea” -# 12345678.1236 e
ce $22,345,678 formatted
PS c:\> “Ch {8xCs) formatted” -# 12345678.1234
1 $22, 345,678.1 formatted
PS C2\3 “C2 {@:C2) formatted” -F 12345678.2236
2 $22,365 678.22 formatted
P = percentage
2S c:\> “Po {8:P0} formactea” -# 0.1236 o
be 12 & formactes
Ps Cx\s "2 {(@:P2) formattea” -f 0.1236
9212.34 € formatted
ose ime o
95 co\> "HO ex{0:X0) fornatted” -* extD2
xe oxtb2 formate
PS c2\> “00 (9:00) formattes” -¢ 12048678 e
9S C:\> “D8 {0:08} formateeg” —-# 123
Ps C2\> "0a (8:08) formattea” = 129
be 123 fornatees
PS C2\> “00 (08:00) formatted” -# 123
»"Note, decimal only supports ints This causes an error:
PS c2\> “00 {2:08} formatees”
Error formatting 2 sting
‘+ "90 (0:08) formatted”
+ Cateporyinto
1 Funtyguatifiedtrrorts
Custom formatting
PS Cry Sites = 286
PS cH\> “There are (:
95 c:\> “Custom 8, 25,
Custon 0, 25. $484
PS c:\> “Custon’8, 25
custon 0, 25 $4, 940.0000 =
PS C21» “Custom 8, 25 $8,H0. 0000
‘0,80, 0600
Se, HF9, 0060
seam
aan e
(00 (0:00) formatted:string) [], Rantinetxcep
80} Lens.” -# $itens
= (0,25:8 04
5 123,456,789.0128
= (0,25:$ 8,440.0
5 123,456, 788.
= {0,25°8 epene.e0) ~
+ ¢ s2seras.cr2
Ps Cr» “Custon 8, 10 etme = {9,t0:R, 880K)
custon 0, 10 #,890% De
PS cot» "Custom 8, 20 #,488,008 = (0, 20:9, 990.008) * =
esc
Date Sting Formatting
= MM Month
= mm=minute
Custom date formating. Note MM is Month, mm is minute
Ny “Today ts (O:M/d/yyyy>. Be well.”
Today 4s 5-3-2017. be well
-# S(cot-vate) Today ss 3/33/2038
PS C2\> “Today $5 (6 20:¥/40/y999). Be wend.” -# S{cot-batey 4 Toaay $5 03/23/2026. be welt
95 c:\> “Today is (6,28:yyyyAmEe). 8 Well.” 2o4n313. Be well.
Today is 20170503. se well
+ s(6er-0ate) 4 Today 1s
PS C2\> “Today $5 (0,20:4/ee/yy9y rsnaes). Be well”
Today 4s 05-23-2017 63:51:58. be well
—————————— »
~# S(s0t-vatey Today ss 03/33/2014 22:21:29. ge
Other formatting
Caleulations can be passed in as the item tobe formatted
PS C2\> “The 20% tip of 2 33.33 dollar BLE Ss {9} dollars” -F (23.33 + 6.28) The 20% tip of 2 33.98 dotiar ot
‘he 20% tip of 2 23.53 dollar E11 4s 6.666 dollars
£053.33
PS C:\> "The 205 tip of 2 33,33 dollar bill as (8. 20) # the 20% tip of 2 33.33 collar il
The 20% tip of 9 93.33 dolar bill 4s 6.67 dollars
——_———EEEEEEEE »
) dodiars*
String operator ike
“+ Teworks using Wildcards
»PS C:\> “Powershell” -1ike “Powers
psc
PS C:\> “Powershell” -1ike “7overshell” fF question marks work for single characters
PS C:\> "Powershell" -2ike "Power*{s-v]" # ends in a char between s and ¥
PS C:\> “Powershell” -Like “Povers(a-c]” # ends tn 2 char between 2 and c
False
String operator -match
‘+ Itworks using Regular Expressions
psa
-308-2240" -naten “[
3)(a}-10
91a"
ps cx\s “772-268
snatch “1
9}(3}-(6
oy"
psc
False
snaten “[0-8}{3}-[0-9]{3}-[0-9] 4)"
5. Working with Arrays
5.41 Simple Arrays
Creating Arrays)
PS C:\> Sareay = “Marendra™, “Bhanubali”
95 c:\> Sarnay
fanshubals
9s c:\> sarrayie)
Ps c:\> Sarraylt]
PS CH\> Sorray.Getrypet)
epublic IsSertst Hane aaserype
True True Object) Systen.Array
‘(Cree
Updating Arrays)
95 co\> sareay
farzck
> facrayle) =
95 c:\> Sareay(t) = “shell”
PS Cy Sarna
ISent
Formal Array Creation Syntax
5 C:\> Sareay = @("Power", “shelI")
95 C219 Sareay
Spell
Conky way to create an empty stray
2 c:\> array = a0)
PS C:\» Sareay.count
PS c:\> array +
ssertray"
PS C19 Sareay 42 “Snover”
95 cH\> S2rvay.count
PS Cy Sarna,
settrey
PS CH» fareay = 3.5. Can lose arrays using nunerse range notation
95 C210 Sareay
ps cis
DS CHAD # Check to S00 4f an Sten exists
2S C:\> Smunvers = 2, 42, 286
25 C:\> Sounvers contains 42
PS C21» Snunvers -notcontsine 99
95 C:\> Snunvers -noteontains «2
False.
52 Array of Arrays
Load four individual arrays
PS Gy sees
Ps coy $02 6.20
Ps Cie $= Mas
PS cy $a = 16..20
facazges
earn)
9S CH\> writesnost “$a = $a 'n'$ = $b nS = $e nS = $e
ses un was mas
I$4 - 16 17 a8 19 20
Now create an array from the four inciviual ones
PS C:\> farvay = 4a, Shy Se, $8
> Sarray
Array wl ow ook lke
CeORCROROEC)
now [0] 2 23 &
now [3] 6 7 8 9
fow [2] 1112 a3 16
few DB] 16 17 38 19
2
Reference the second item in the second array (remember arrays are 0 based)
PS C:\> Sarray[t][2] # zero bases array, g0 to 2nd row, 3rd teen
‘Toke the contents ofthe aray and join them into single string,
Ps c:\> $2rrayle) ~Join * *
vases
PS C213 Sareayi2] ~Join”
5 c:\> Sarray(3) ~Join * *
ae 17 3829-28
2 cs\> Sarraylt] {2}
Ps c:\> $array(3)(3]
6. Hash tables
> $hash = 6CCKey
bowershell™
“yettrey snover
PowerSnell con"
“PowerShell Inventor")
S
»Ps cx» has
Powershell
Jeffrey snover
By default, the hashes doesnt store the keys inthe order of assignment. If we need to retain the asigned order,
vate
PowerShell.com
value
PowerShell tnventor
9 C1\> haan = [onderedO("Key™ = value":
o> “Powershell” = “Powershell con”;
> sJettrey snover = "Powershell Inverter")
5 c2\> hasnt
key
setfrey snover
valve
PowerShell inventor
Values from hash key canbe retrieved in two ways
25 c:\> $hasht"Powershel1")
2S C2\> hash. "Jerrey snow
Powershell Inventor
You can use variables as keys
PS Cy Sayeey = “Powerset
25 C2\> hash. sayhey
Powershell.com
PS co\> hash. s¢Smykey)
# Get 2 single value fron the key
1 Get single value using object syntax
evaluating 3s an expression
95 C:\> $hash.S¢°Power” + "Shell”)
Powershell .cow
[Adding and removing values
PS C2\> hash
Powershell
Jeftrey snover
95 C:\> $hasn("aws"} = "Aa
Ps cr» has
Powershell
effrey snover
valve
Powershell com
eb Services™ # AUG value using new Key
show the agestionsl row
PowerShell com
snazon Web Services
»PS C:\> Shash.tenove( “Jer rey snover") 1 tenove by passing tn key
PS C219 hash
none value
key value
Seeit key exists
False
Seeit value exists
5 C:\> shash.ContatneValue(“PowerShell Enventor") # Mot there since it was renoved
alse
Listkeys and values
PS CAs fhash.ceye
PS C21» shash.values
Powershell eon
vale
Findif key or values present
PS Cx» Shasn.xeys -contains “Powershell”
> Shash.values -contatns “PowerShelt.con”™
7. Conditional Statements and Loops
TAiffelse condition
Ps cts fear = 2
4¢ (Svar eq 1) #64 sure to use -eq instead of =
‘
"2 branen™
)
ase
‘
> smash. containe( ams") + should ne there
> Sash. Contains ("Jeffrey Snover") Gone since we Just removed st
> shasn.containsvalue(“Pouersnellcon") # Will be there
»)
‘se branch
72 else
9s cop far = 2
6 (Svar -2q 1)
‘
“1 seq 1 brane”
>
elseif (Svar -e0 2)
‘
elsert eq 2 branch
>
<
else branch”
)
173 Switch case
95 C:\> # switch statement for multiple conditions
svar 2 fF wlso cose with 43 ane 49
seiteh (Svar)
‘
a (Forty one"?
42 ("Forty Two")
43 ("Forty Three")
default ("aefaule”)
>
Forty Two
PS C:\> # MALL match all Lines that match
bs C110 far = a2
switch ($4ar)
‘
42 (Footy TH"?
san Crorty Tne string”)
Gefault ("aefault")
>
Forty Two steing
Note that ype coercion will ause both 2 lines tohave a match.
‘Tostop processing once a block s found use break
Ps c:\> fear = a2
snitch (Sear)
‘
42 (*ronty Two"; break)
sant (Chorey Ive String”; break)
default ("aefauie)
>
Note, it you want to put multiple commands ona single ine, use ato seporate them
‘Switch works with collections, loping and executing fer each match
PS c2\> suiten (2,5,2,42)
‘
1 Cone")
2 CTW")
2 Che
S
»efaunt ("THe default ansver”)
>
‘he cetault answer
String compares ate case insensitive by default
Ps cats muster ¢
4
“pouershelI” ("Lowercase")
“POWERSHELL” ("uppercase")
ponershell” ("nbeedease”)
)
uppercase
rixeccase
lershel3")
Use the -casesenstive switch to make itso
‘
“powershel1" ("Lowercase")
"POWERSHELL" {"uppercase”}
powershell” (°nteedcase")
>
nixeccase
> switch -casesensivive ("Powershell")
Supports wildeardés
PS Ci\> susten -wdcard ("Pluralsient”)
‘
splurate™ (0°)
churatstane” C27)
sphuratsi72" C2?)
>
mm
[Note that will also support regex matches.
74 While Loop.
95 cr\> # unite
sina
vite (84 -te 5)
‘
vee
siesiea
)
sina
sie?
sie
sis
gies
PS C:\> # Maile won't execute if condition 3s already true
see
vette ($4 -1e 5)
»tee
seated
175 do-While
PS C2\s # dowwntle
sist
‘
wats se
sus
2) whtte(si Te 5)
rs
soe
sis
sina
ses
Do wil always execute atleast once
see
era
see
) white($i “te 5)
site
Use until to make the check more positive
sien
‘
ate
sie
) untiness -ae 5)
song
sin?
sie
sisa
gies
76 for loop
Ps cas for OF
‘
wae ese
$6 Te 5: $400)
[Note the intiaizer can beset seperately
osc $e?
for (5 $6 “le 8; $t00)
‘
ose ese
>
Ise
5
st
st
erating over a collection 1 by 1
95 c:\> Sarvay = 22,12,13,18,35 Simple Array
for (S800; $1 -18 Saeray. Lengths $ie4)
‘
sanray( ss
>
Sarray(a}=11
Sarraytx}-12
sarray(2}-13
Sarray{3}-16
Sarray(e}-15
+ sarrayist]
77 foreach
foreach works on acolection
95 C:\> Sarray = 12,12,13,18,35 Staple Array
oreach ($iter in serray)
‘
wSiten = sitent
>
sisen = 22
siten = 12
Sisen = 23
Siten = 26
sien = 15,
Ps ci\> “reaes a4)"
ps Col> "amas (on)*
95 C29 "360=s(108)*
ps cr\> "aTaes(aT8)
18-2099511627776
2s cs\> “199-5(398)"
PS c:\> foreach(si in @C'2K8', "2M", "166", "118",
Dyweite Host 51 =808)")
foreach works with an array of objects
‘
St0.tone
>
Scripts
fl
> foreach ($file An Ger-Childisen -Path °e:\Python7")
Isoos
License et
pythonw.o¥e
Use break to get out ofthe loop
2 c:\» foreach ($FE2e In Get-childtten path "e:\Python2?")
4
£6 (Seste.nane -26ke “*exe")
‘
seston
break # exits the loop on first nit
>
>
Use continue to skip the rest ofa loop but go onto the next iteration
PS Ci\> foreach (SFL2e An Get-childzten -Path "Cs\Python27")
‘
4F ($FSle.nane -26ke "*.exe")
‘
continue # exits the loop on first het
?
"This Sone a executante Fite: $4te
>
nis dan't a executable Fle: oe
This Len°t a executable fie: ote
This fen°t 3 executable file: Sneluge
nts tan't a executable file: Scripts
nis fan't 3 executable file: snare
nis isn't 3 executable fle: HEWS.Oxt
python.exe
This tent a executable Fe: READHE. xt
\axpopen exe
‘When used in nested loop, break exits to the outer loop
P5 c:\> foreach (foutsise tn 2.3)
Soutsidena
Sinside = 4
Soutside-2,
Sinsige » 4
Sinsice = 4
Use oop labels to break toa certain loop
S
S
Ipsc
‘
~ souresde-sovtssce”
foreach (Sinsiae én 4.6)
4
* “sinsige = sinsige”
break outsigeloep
?
>
Soursidena
Sinside = 4
yatstdeloop foreach (Soutsige tn 2..3)
Using continue inside an inner loop
foreach (Soutsige tn 1.43)
foreach (Sinside én 4.6)
‘
+ Sinstue = ginstse
“this will never execute as continue goes back fo start of inner for Loop
4 note, seeaure me continue to the inside Toop, the a90ve Line
4 ws1l never run but 48 will go thru all Sterations of the inner esp
>
>
Soureicena
Sinsige = 4
‘insiae = 5
inside = 6
Seutsiden2
Sinsige = 4
Sinsige = 5
Sinise = 6
Soutside
Sinsige = 4
sinsice = 6
PS C2\> souestdeloop foreach (Soutside Am 2.3)
4
" soutsidessoutsiae
foreach (Sinsise in 4.6)
‘
+“ $instae = Sinaia’
“ibis will never execute as continue goes back fo start of toner for Loop
here, vecouse we break all the may to the outer Joop the Last two
4 tterations (5 and 6) never run
>
>
Soureidera
Sinsice = 4
Soutside-2
Sinsige = 4
Soutsia
Sinsige = 4
7.8 Script Blocks
[basic script block is code inside 0. The for (as well as other loops) execute a serpt block
95 C29 for (SF = OF $# Le 5: $444)
‘
see se
?
S
Isree
seen
seo?
seo
seoa
SF = SPS c:\> for (56
‘
ae ee
>
0 $6 le 5) $408)
see
are
se
are
st
are
A scrip block can exist on is oven.
NOTE: To put multiple commands ona single line use the
PS C2\> (Clear-Host: “Pomershenl is cool“)
Executing only shows the contents ofthe block doesn't execute
‘To actualy rum it use an ampersand & infront
25 C:\> A(Clear-Host; “Powershell 1s co0t.-)
You can store srt blocks inside a variable
PS C:\> Scool = (Cear-Host; “Powersnell 1s c001.")
ust entering the variable though only shows the contents, doesn run
PS Cx\sClear-tost; “Powershell $e exo1.”
PS C2\> & $eool a Te actually run it, use the & character
Powershell is cool.
Since scripts canbe put ina variable, you can do intersting things.
PS C:\> $co0] ~ (Powershell 4s cool"; * S045 Seffrey srover")
for ($ie0;$4 It 35 $488)
‘
scoot:
>
Powershell 45 cool.
So ts jeffrey srover
fo is Jeffrey snover
So 1s jeférey srover
8. Functions
PS Cy swe ¢
Hete wore”
>
S
»