You are on page 1of 15

The Administrator Crash Course

Windows PowerShell v2

Don Jones

PowerShell Crash Course

Don Jones

IntroductiontoRealtimePublishers
by Don Jones, Series Editor

Forseveralyearsnow,Realtimehasproduceddozensanddozensofhighqualitybooks
thatjusthappentobedeliveredinelectronicformatatnocosttoyou,thereader.Weve
madethisuniquepublishingmodelworkthroughthegeneroussupportandcooperationof
oursponsors,whoagreetobeareachbooksproductionexpensesforthebenefitofour
readers.
Althoughwevealwaysofferedourpublicationstoyouforfree,dontthinkforamoment
thatqualityisanythinglessthanourtoppriority.Myjobistomakesurethatourbooksare
asgoodasandinmostcasesbetterthananyprintedbookthatwouldcostyou$40or
more.Ourelectronicpublishingmodeloffersseveraladvantagesoverprintedbooks:You
receivechaptersliterallyasfastasourauthorsproducethem(hencetherealtimeaspect
ofourmodel),andwecanupdatechapterstoreflectthelatestchangesintechnology.
Iwanttopointoutthatourbooksarebynomeanspaidadvertisementsorwhitepapers.
Wereanindependentpublishingcompany,andanimportantaspectofmyjobistomake
surethatourauthorsarefreetovoicetheirexpertiseandopinionswithoutreservationor
restriction.Wemaintaincompleteeditorialcontrolofourpublications,andImproudthat
weveproducedsomanyqualitybooksoverthepastyears.
Iwanttoextendaninvitationtovisitusathttp://nexus.realtimepublishers.com,especially
ifyouvereceivedthispublicationfromafriendorcolleague.Wehaveawidevarietyof
additionalbooksonarangeoftopics,andyouresuretofindsomethingthatsofinterestto
youanditwontcostyouathing.WehopeyoullcontinuetocometoRealtimeforyour
educationalneedsfarintothefuture.
Untilthen,enjoy.
DonJones

PowerShell Crash Course

Don Jones

IntroductiontoRealtimePublishers.................................................................................................................i
PowerShellCrashCourseWeek1.....................................................................................................................1
PreRequisites.......................................................................................................................................................2
Week1,Day1:Commands,Cmdlets,andAliases..................................................................................2
Week1,Day2:Output.......................................................................................................................................4
Step1:FindAttributes..................................................................................................................................4
Step2:PickaLayout.....................................................................................................................................5
Step3:AddYourProperties.......................................................................................................................5
Format,ThenYoureDone..........................................................................................................................6
Week1,Day3:ThePipeline...........................................................................................................................6
Step1:DetermineYourOutput................................................................................................................7
Step2:FindMatchingInputTypes.........................................................................................................7
Step3:WhenTypesArentEnough........................................................................................................8
Week1,Day4:CoreCmdlets..........................................................................................................................9
Week1,Day5:ConfigurationBaselines.................................................................................................10
DownloadAdditionalBooksfromRealtimeNexus!..........................................................................11

ii

PowerShell Crash Course

Don Jones

Copyright Statement
2010 Realtime Publishers. All rights reserved. This site contains materials that have
been created, developed, or commissioned by, and published with the permission of,
Realtime Publishers (the Materials) and this site and any such Materials are protected
by international copyright and trademark laws.
THE MATERIALS ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
TITLE AND NON-INFRINGEMENT. The Materials are subject to change without notice
and do not represent a commitment on the part of Realtime Publishers its web site
sponsors. In no event shall Realtime Publishers or its web site sponsors be held liable for
technical or editorial errors or omissions contained in the Materials, including without
limitation, for any direct, indirect, incidental, special, exemplary or consequential
damages whatsoever resulting from the use of any information contained in the Materials.
The Materials (including but not limited to the text, images, audio, and/or video) may not
be copied, reproduced, republished, uploaded, posted, transmitted, or distributed in any
way, in whole or in part, except that one copy may be downloaded for your personal, noncommercial use on a single computer. In connection with such use, you may not modify
or obscure any copyright or other proprietary notice.
The Materials may contain trademarks, services marks and logos that are the property of
third parties. You are not permitted to use these trademarks, services marks or logos
without prior written consent of such third parties.
Realtime Publishers and the Realtime Publishers logo are registered in the US Patent &
Trademark Office. All other product or service names are the property of their respective
owners.
If you have any questions about these terms, or if you would like information about
licensing materials from Realtime Publishers, please contact us via e-mail at
info@realtimepublishers.com.

iii

PowerShell Crash Course

Don Jones

[EditorsNote:ThisbookwasdownloadedfromRealtimeNexusTheDigitalLibraryforIT
Professionals.AllleadingtechnologybooksfromRealtimePublisherscanbefoundat
http://nexus.realtimepublishers.com.]

PowerShellCrashCourseWeek1
BynowyouveprobablygottenthemessageloudandclearthatWindowsPowerShellis
prettyimportant;Microsoftisaddingittomoreandmoreproducts,andgoingforward,the
companysplanistoincorporatePowerShellthroughoutallofitsbusinessproductsasa
baselineadministrativelayer.No,theGUIisntgoingawayitsstillcalledWindows,
afterallbutinmostcases,theGUIwillsimplyberunningPowerShellcommandsunder
thehood.Insomecases,theGUIwillbedeemphasized,meaningtheGUImightnot
surfacealloftheproductsadministrativefunctionality.
IfyourereadytogetstartedinPowerShell,andhavenoexperience,thisisthecrashcourse
foryou.IfyouhaveabitofUnixorVBScriptexperience,trytoremovethatfromyourbrain:
PowerShellwilllookfamiliar,butitsreallysomethingverynewanddifferent.
Iencourageyoutocontinueexploringbeyondthiscrashcourse,too.Forexample,visit
http://windowsitpro.com/go/DonJonesPowerShelltofindtipsandtricksandFAQsandto
askquestions,ordropbythePowerShellteamsownblogat
http://blogs.msdn.com/powershellforinsiderinformation.Youllalsofindalotofin
personPowerShellinstructionateventslikeTechMentor
(http://www.techmentorevents.com)andWindowsConnections
(http://www.winconnections.com).
HowtoUsethisCrashCourse
Isuggestthatyoutackleasinglecrashcourseitemeachday.Spendsome
timepracticingwhateverexamplesareprovidedandtryingtocompletetasks
thatmakesenseinyourenvironment.Dontbeafraidtofail:Errorsarehow
welearn.Justdoitinavirtualenvironment(Irecommendavirtualized
domaincontrollerrunningWindowsServer2008R2)sothatyoudontupset
theboss!EachDayinthiscrashcourseisdesignedtobereviewedinunder
anhour,soitsaperfectwaytospendlunchforafewweeks.Thisbookwill
bepublishedinfivedayincrements,soeachchaptercorrespondstoasingle
weekoflearning.

PowerShell Crash Course

Don Jones

Bytheway,thiscrashcourseisntintendedtobecomprehensiveIalreadycoauthored
WindowsPowerShellv2:TFManddontintendtorewritethesamebookhere!Instead,this
isdesignedtogetyouupandrunningquicklywiththemostcrucialelementsoftheshell.
Imskippingoveralotofstufftogetrighttothereallygoodbits,andinsomecases,Imay
glossovertechnicaldetailssimplybecausetheydontcontributetospeedyunderstanding
ofthemostimportantthings.Youshouldobviouslykeepexploring;inmyblog(linked
earlier),forexample,Igointoalotoftheselittledetailsinoneshortarticleatatime.Youll
alsofindPowerShellvideotipsonhttp://nexus.realtimepublishers.com,andthosecanhelp
youembracesomeofthemoredetailedthingsthatImightskiphere.

PreRequisites
PowerShellv2comespreinstalledonWindows7andWindowsServer2008R2;its
availableasafreedownload(fromhttp://download.microsoft.com)forWindowsXP,
WindowsServer2003,WindowsVista,andWindowsServer2008.Besuretodownloadthe
rightversionforyouroperatingsystem(OS)andarchitecture(32or64bit).Youllneed,
ataminimum,.NETFrameworkv2installed.Ideally,getthelatestversionofthe
Framework,oratleastv3.5ServicePack1,becausethatenablesmaximumWindows
PowerShellfeatures.
WindowsServer2008R2shipswithanumberofPowerShellmodulesthatconnect
PowerShelltoActiveDirectory(AD),IIS,BitLocker,andothertechnologies.Generally
speaking,thesemoduleswillonlyrunonWindowsServer2008R2or,ifyouinstallthe
RemoteServerAdministrationToolkit,onWindows7.Theresatrickcalledimplicit
remoting(Illgettoit)thatletsyouaccessthesecmdletsfromolderOSsthathave
PowerShellv2installed,butyoullneedatleastoneWin7orWin2008R2machineonyour
networktohostthecmdletsforremoteuse.

Week1,Day1:Commands,Cmdlets,andAliases
PowerShellisnot,firstandforemost,ascriptinglanguage.Itsashell,notunlikeCmd.exe.
Itswrittenin.NETinsteadofC++orsomething,butintheenditsatextbasedcommand
linewindow.Youtypecommands,hitEnter,andtheyrunandyouseeresults.
Goon,tryit.RunPing,Ipconfig,NetShare,orwhateverothercommandsyoumayknow.
Theyllwork.Thosethreespecificallyareexternalcommands,meaningtheyexistas
standalone.exefiles.PowerShellalsohasnativecommands,whicharecalledcmdlets
(pronouncedcommandlets).Thedifferencewiththeseisthattheyonlyrunwithin
PowerShell;youcantgettothemfromCmd.exeorfromExploreroranywhereelse.
ExamplesincludeDir,Cd,Del,Move,Copy,andType.Yep,thoselookjustlikecommand
namesyoureprobablyfamiliarwith.YoucantryLs,Cat,andCpwhileyoureatit,because
thosewillallwork,too.

PowerShell Crash Course

Don Jones

Buttheywontworkinquitethesamewaythatyoureusedto.Thoseareactuallyaliases,
ornicknames,toPowerShellcmdlets.TherealcmdletnamesarethingslikeGetChildItem,
SetLocation,RemoveItem,MoveItem,CopyItem,andGetContent.Thealiasesexist
togiveyousomethingabiteasiertotypethatcorrespondstotheMSDOSstylecommand
namesthatyoureprobablyfamiliarwith.Thesenewcmdletsandtheiraliaseswork
similarlytothoseoldschoolcommands,buttheygetthereinadifferentway.Forexample,
tryrunningDir/sinPowerShell;youllprobablygetanerror.RunHelpDirandyoullsee
whyyougotanerror:Theresno/sparameter.
InPowerShell,parametersallbeginwithadash()notaslash(/),andparameternames
tendtobefullwords,likerecurse.SorunningDirrecursewillworkjustfine.Actually,you
donthavetotypethefullparametername;youonlyneedenoughsothattheshellcan
uniquelyidentifyit.Dirrwillprobablyworkfine.Andno,youcantbuildanaliasthat
wouldmakeDir/swork;aliasesarejustanicknameforthecmdletname.Aliasesdont
haveanyeffectontheparametersofthecmdlet.
ThatHelpcommandisgoingtobeyournewbestfriendorithadbetterbe,ifyouplanto
masterPowerShell.RunHelp*foralistofallhelptopics;noticethenumerousabout
topicsthatdontrelatetoaspecificcmdletbutinsteadcoverbackgroundconcepts.Thats
yourmanual(infact,youcanusetheUnixstylealiasManinsteadofHelpifyouprefer).
RunHelp*service*toseeeverythingthathastodowithservices,orHelp*user*toseeif
theresanythingintheretodealwithuseraccounts.
Whilewereatit,noticethecmdletnames:Theyhaveaspecificnamingpattern,consisting
ofaverb,adash,andasingularnoun(itsGetService,notGetServices).Theverbscome
fromastrictlycontrolledset:ItwillalwaysbeNewandnotCreate,andyoullneversee
DeleteinplaceofRemove.Theseconsistentverbnames,combinedwithcommonnouns
suchasService,Process,EventLog,andsoforth,makeiteasiertoguessatacmdletname.
CanyouguessthecmdletprovidedbyExchangeServertoretrievemailboxes?Get
Mailbox.WhatcmdletintheADmodulemightretrieveauseraccount?GetADUser.Yeah,
sometimesyoullseeaproductspecificprefix,suchasAD,attachedtothenoun.That
helpsdistinguishitfromotherkindsofuseraccountsthatmightexistinyourenvironment.
Tryrunningsomesinglecommands.Stuckforideas?RunHelp*togetalistofhelptopics,
whichwillincludeallthecmdlets,thenrunHelpcmdletnameexample.Addingthe
exampleparameterretrievesalistofexamplesforthatparticularcmdletveryhandy!

PowerShell Crash Course

Don Jones

Week1,Day2:Output
RunningDirandsoforthcertainlyproducestextonthescreen.Butletslookatwhytextis
bad.
IntheUnixworld,everythingistextbased.Runacommandthatgeneratesalistofrunning
processes,andyoullseeatextlistlaidoutasacolumnartable.AUnixadminlookingfora
particularprocessnamemightpipethattexttoacommandlikeGrep,tellingittofilterout
entirerowsbasedonthecontentsofcolumns8through16,whichcontainedprocess
names.Thatkindoftextparsinghasbeenacommontaskinmostshellbased
administration.Itstoughbecauseitrequiresexactitudeandoftenalotof
experimentationthatgoesbeyondtheactualadministrativetask.PowerShelldoesnt
workthatway.
Instead,PowerShellcmdletsproduceobjects,whichareessentiallyaspecializeddata
structureinmemory.Insteadofputtinginformationintotablesandlists,informationgoes
intothisspecializedstructure.Thebenefitofthisstructureisthatyoucanasktheshellfor
asinglepieceofinformation,anditcaninstantlyretrieveitwithoutyouhavingtoknow
exactlyhowthestructureisbuilt.Inotherwords,youdontasktheshelltolookatthe
contentsofcolumns8through16;youjustaskittolookattheprocessnames.Theshell
knowswhichbitofthedatastructurecontainsthenamesothatyoudonthavetoknow.
Thisturnsouttobeprettypowerful,asyoullseeshortly.Butyoumightaskyourselfwhy
PowerShellcmdletsstillseemtoproducetext.Well,thatsbecausetheshellknowsthatyou,
poorhumanbeingthatyouare,cantcomprehendthewondrousdatastructuresstoredin
yourcomputersmemory.Sowhentheshellfinishesrunningcommands,itconvertsall
thoseobjectsintotextbasedtablesandlistsforyou.Essentially,itretrievessomeofthe
objectsattributesfromtheinmemorydatastructureanddynamicallyconstructsatext
basedtableorlist.
Youcanactuallyexerciseatremendousamountofcontroloverthisprocess,orjustsitback
andletthedefaultstakeover.Ifyouarentlikingthedefaults,therearereallythreesteps
youneedtotake.

Step1:FindAttributes
Everyobjectthattheshellworkswithhasnumerousattributesorproperties.Forexample,
aprocesshaspropertiesforitsname,ID,memoryconsumption,andsoforth.Toseealist
ofthemall,pipetheobjecttoGetMember(whichhasanalias,Gm).Forexample,Get
Process|Gmwillshowyouthepropertiesofaprocess;GetService|Gmwillshowyou
thepropertiesofaservice.
Hint
AnycmdletthatusesGetasitsverbwillusuallyproducesomekindofobject
thatcanbepipedtoGetMember.
Makeanoteofthepropertiesthatyouthinkyoudliketosee.Justwritedowntheirnames,
fornow.

PowerShell Crash Course

Don Jones

Step2:PickaLayout
PowerShelloffersthreedefaultlayouts:tables,lists,andawidelist.Decidewhichoneyou
thinkwillworkforyourneeds.Keepinmindthattablescanonlyholdsomanycolumns
withouttruncatinginformation,soifyouveselectedaLOTofproperties,alistmightbe
appropriate.Awidelistonlydisplaysasinglepropertysomethingelsetokeepinmind.
Onceyouvechosenalayout,youllpipeyourobjectstoit:GetProcess|FormatList,for
example,orGetService|FormatWide,orGetEventLogSecuritynewest20|Format
Table.ThealiasesforthoseFormatcmdletsareFL,FW,andFT,respectively.
Hint
Theshellisntcasesensitiveaboutcmdletoraliasnames.FTisthesameas
Ft,ft,andfT.

Step3:AddYourProperties
Bydefault,theshelldecideswhatpropertiesareshowninatableorlist,anditdefaultsto
theNamepropertyforwidelists.Customizethatbyjustprovidingacommaseparatedlist
ofproperties:GetProcess|FLName,ID,VM,CPU.Ifyoujustwanteverypropertyshown,
use*forthepropertylist:GetService|FL*.
AdditionalparametersoftheFormatcmdletsenablefurthercustomization.Seeifyoucan
answerthesequestions:

Ifyouuseatablewithonlyacoupleofproperties,suchasGetService|FT
Name,Status,youllnoticealotofunusedspaceonthescreen.Whatparameterof
FormatTablemighteliminatethatextraspaceandinsteadautomaticallysizeeach
columnforitscontents?

Ifyouincludetoomanycolumns,FTmaytruncatetheircontents.Whatparameter
wouldinsteadforceittowordwrapthatinformation?

FWdefaultstotwocolumns.Howcanyouhavealistoffourcolumns?

PowerShell Crash Course

Don Jones

Format,ThenYoureDone
AtrickabouttheFormatcmdletsisthattheyconsumewhateveryoupipeintothem.They
outputaspecialkindofformattinginstructionthatreallyonlymakessensetotheshell
itself.TryrunningGetProcess|FT|GMandyoullseewhatImean.Thepracticalupshot
ofthisisthataFormatcmdletwillalmostalwaysbethelastthingonthecommandline.
Almostalways?YestheonetypeofcmdletthatcanunderstandFormatoutputisanOut
cmdlet:OutHost,OutPrinter,OutFile,andsoforth.Infact,OutHostistheoneusedby
defaultintheconsolewindow,butyoucanpipeformattedoutputtotheotherOutcmdlets
toredirectoutputtoaprinter,afile,orelsewhere:

IfyoudirectoutputtoOutFile,thefilewidthdefaultsto80characters.Whatifyou
wantedtopipeoutamuchwidertableofinformation?Isthereaparameterthat
wouldletyoumodifythelogicalwidthofthefile?

Whatparametersallowyoutospecifyadestinationprinterwhenpipingoutputtoa
printer?

CanyoupipeoutputdirectlytoanOutcmdletwithoutusingaFormatcmdlet,such
asGetService|OutFiletest.txt?

Week1,Day3:ThePipeline
Youvealreadystartedpipingstufffromonecmdlettoanother,soitshouldcomeasno
surprisethatPowerShellcmdletsruninapipeline.Essentially,apipelineisjustasequence
ofcmdlets:
GetService|SortStatusdescending|FormatTablegroupByStatus
Thepipe|characterseparateseachcmdlet.Eachcmdletplacesthingsintothepipeline,and
theyarecarriedtothenextcmdlet,whichdoessomethingwiththem.Thenthatcmdlet
placessomethingintothepipeline,whichcarriesittothenextcmdletandsoon.Thiscan
createsomeprettypowerfulonelinecommands,andthankstotheshellscmdletnaming
syntax,theycanbeprettyeasytofigureout.Forexample,considerthispseudocommand:
GetMailbox|SortSizedescending|Selectfirst10|MoveMailboxServer2
Thatsnottheexactcorrectsyntax,buthopefullyitconveysthepoweroftheshellscmdlet
interaction.Thetrickisthateverycmdletgetstodecidewhatkindofinputitwillaccept.In
otherwords,youcantjustpipeanythingtoanything.Thiswouldmakenosense:
GetADUserfilter*|StopService
TheresnoreasonwhypipingauseraccounttoStopServiceshouldmakesense,andin
factitwontwork.Sohowcanyoutellwhatacmdletiswillingtoacceptasinputfromthe
pipeline?Thereare(aswillbecomeathemeinthiscrashcourse)threesteps.

PowerShell Crash Course

Don Jones

Step1:DetermineYourOutput
First,cmdletsthatproduceoutputare,aswealreadylearned,producingobjects.Thething
is,notallobjectsarebuiltthesame.Aprocesslooksverydifferentfromaservice,for
example,whichisentirelydifferentthananeventlogentryorauseraccount.So,each
objecthasatypename,whichsimplydescribesthekindofobjectyourelookingat.Piping
objectstoGetMemberrevealstheirtypename.RunGetService|Gmandseeifyoucan
findthetypename.Goon,Illwait.
waits
ItsaServiceController,right?Youcanoftenjusttakethelastsegmentofthetypename.
Nowtheresjustonetrick:Allobjectsaretechnicallyofwhatevertypetheyareandtheyare
themoregenericobjecttype.ThatslikesayingyoureaHomosapien,whichisavery
specifictypename,andthatyourealsoanorganism,whichismuchmoregeneric.Object
isjustaverygenericclassificationforobjecttypes.
Ok,sonowyouknowwhatyouhaveasyourcmdletoutput:Agenericobjectaswellas
somemorespecifictypename.Now,whatcanyoudowithit?

Step2:FindMatchingInputTypes
RunHelpStopServicefull(youllfindthatthefullhelpisoftenthemostuseful).Start
lookingatthebreakdownforeachparameter.Noticehoweachparameterhastheoptionto
Acceptpipelineinput?ItsFalseformanyofthem.Infact,forStopService,thefirstone
thatsTrueistheinputObjectparameter.Morespecifically,itacceptspipelineinput
ByValue,itsaysinthehelp.Lookingattheparameterdefinition,youllseethatthetypeof
objectitacceptsisServiceController.Wait,wherehaveweseenthatbefore?
Sohereshowitworks:
1. Youpipeobject(s)fromonecmdlettoanother.
2. Thereceivingcmdletlooksatthetypenameoftheincomingobjects.
3. Thereceivingcmdletlookstoseewhetheranyofitsparameterswillacceptpipeline
inputByValueforthattypename.
4. Ifitfindsone(andtherewillbezeroorone,butnotmore),theinputobjectsare
giventothatparameter.
Sothatswhythisworks(anditllcrashyourmachine,sodontrunit):
GetService|StopService
ItworksbecauseGetServiceproducedServiceControllerobjects.Thosewerepipedto
StopService,whichquicklyrealizedthattheinputObjectparameterwaswillingtoaccept
objectsofthattype(whichiswhatByValuemeans).Sothoseserviceswerehandedoffto
theinputObjectparameter,specifyingtheservicesthatshouldbestopped.

PowerShell Crash Course

Don Jones

Readingthathelpfileabitmore,youllnoticethatNamealsoacceptsinputByValue.Its
valuetypeisString,meaningifyoupipeinastringofcharacters,theyllbeattachedtothe
Nameparameter,specifyingtheservice(s)tostop:
BITS|StopService
BITS,TrustedInstaller|StopService
Tip
Whenyoumakeacommaseparatedlistofvalues,PowerShelltreatsthemas
asinglegroup,sothosetwovaluesarepipedinasaunit.Becausetheyre
bothoftheStringtype,theyllbothattachtotheNameparameter,andboth
serviceswillbestopped.
AndhowdidweknowthatBITS,TrustedInstallerwerestrings?ByusingGetMember,
ofcourse!
BITS,TrustedInstaller|GM
TheyreclearlyidentifiedasaSystem.String(justStringforshort)bytheoutputofGet
Member.

Step3:WhenTypesArentEnough
Now,theshellisntsupersmart.Itwilltrytodostuffthatdoesntmakesense,ifyoutellit
to.Forexample,considerthis:
GetProcess|StopService
Makesnosense,right?Well,letslookatitfromtheshellspointofview.GetProcess
producesobjectsthat,accordingtoGetMember,areoftheSystem.Diagnostics.Process
type.Great.LookingthroughthehelpforStopService,Idontseeanyparametersthatwill
bindaProcessobjectByValue;Ialsodontseeanythatwouldbindthemoregeneric
objectByValue.SoacceptingpipelineinputByValuewillfail.
Buttheshellhasabackupplan:AcceptingpipelineinputByPropertyName.ForStop
Service,youllseethisonlyontheNameparameter.Whatdoesthismean?
1. Youpipeobject(s)fromonecmdlettoanother.
2. Thereceivingcmdletlooksatthetypenameoftheincomingobjects.
3. Thereceivingcmdletlookstoseewhetheranyofitsparameterswillacceptpipeline
inputByValueforthattypename.
4. Ifitdoesntfindone,whichisthecaseinthisexample,itwilllooktoseewhat
parametersacceptpipelineinputByPropertyName.
5. Itwillthenattachthoseparameterstothepropertiesoftheincomingobject(s)that
haveamatchingname.Inotherwords,iftheincomingobjectshaveaName
property,thevalueofthatpropertywillgointotheNameparameterofStop
Servicesimplybecausethenamesmatch.

PowerShell Crash Course

Don Jones

Remember,thisisPlanB,soitonlygoesintoeffectwhennothingcouldbeboundtoa
parameterByValue.SoweresittingherelookingataNameparameterthatwantstotake
pipelineinputByPropertyName.WevegivenitProcessobjects.DothoseProcessobjects
haveaNameproperty?AccordingtoGetMember,theydoindeed!SotheNamepropertyof
theinputobjectswillbepassedtotheNamepropertyofthecmdlet.Theresultisthatthe
StopServicecmdletwilltryandstopservicesbasedontheirprocessname.Inmanycases,
itwillbeabletodosobecauseaservicesnameisoftenthesameasthenameofitsprocess
whentheserviceisrunning.
Soyouhavetobeabitcarefulwiththisbusinessofpipingobjectsfromonecmdletto
anothersometimesitllworkbetterthanyouthink,whichmightbeworsethanyouwant.

Week1,Day4:CoreCmdlets
Nowthatyouknowhowtopipestufffromonecmdlettoanother,youmightwanttolearn
someofthecmdletsthatcanletyoumanipulateobjectsinthepipeline.Imgoingtobriefly
introducetheseandgiveyouaquickexample,butImgoingtoexpectyoutoreadthehelp
tolearnmoreaboutthemandIllasksomefinishingquestionstohelpencouragethat
independentresearch:

SortObject,oritsaliasSort,rearrangesobjectsinmemory.Justspecifythe
propertyyouwanttosortthemby,suchasGetProcess|SortID.

SelectObjectdoesalotofstuff,andyoulloftenseeitsalias,Select.Fornow,focus
onitsabilitytograbjustthefirstorlastobjectsinthepipeline:GetProcess|Sort
VM|Selectfirst10.

MeasureObjectcountsobjects.Ifyouspecifyaproperty,youcanalsohaveit
averagethevaluesforthatproperty,assumingitcontainsnumericvalues.Itsaliasis
justMeasure:GetProcess|Measurevmaverage

ImportCSVandExportCSVreadandwriteCommaSeparatedValues(CSV)files,
likethis:GetService|ExportCSVservicelist.csv

ConvertToHTMLcreatesanHTMLtable.YoullprobablywanttowritetheHTML
toafile:GetEventLogSecuritynewest10|ConvertToHTML|OutFile
securityevents.htm

Nowsthetimeforthatindependentresearch.Howwouldyou:

ChangethesortorderofSorttobedescendinginsteadofascending(whichisthe
default)?

Getthelast20objectsfromthepipelineusingSelect?

ChangethedelimiterofaCSVfiletoapipe|characterinsteadofacomma?

Displaynotonlytheaveragevalueforprocessingphysicalmemorybutalsothe
minimumandmaximumvaluesandthetotalphysicalmemoryused?

Themorecomfortableyoubecomereadingthehelp,themorecapabilitiesyoullfind!

PowerShell Crash Course

Don Jones

Week1,Day5:ConfigurationBaselines
ThisisthelasttipforyourfirstweekofPowerShell,anditsadoozy.Firstupisapairof
cmdletsthatreadandwriteXMLformattedfiles:ImportCliXMLandExportCliXML.For
example,letsexportalltherunningprocessestoafile:
GetProcess|ExportCliXMLbaseline.xml
Now,launchacouplemoreprocesses:
Notepad
Calc
Mspaint
NowforafunnewcmdletcalledCompareObject,orDiffasusslowtypistsliketocallhim.
Thiscmdletisntthatgoodatcomparingtextfiles(remember,PowerShellkindahates
text),butitsawesomeatcomparingsetsofobjects.Considerthiscommand:
Diff(Ps)(ImportCliXMLbaseline.xml)
Coupleoffunthingshappeningthere.First,PSisjustanaliasforGetProcess.Thereally
funthingistheplacementoftheparameters.Yousee,Ishouldreallyhavewrittenthe
commandlikethis:
DiffreferenceObject(Ps)differenceObject(ImportCliXMLbaseline.xml)
Thistime,Imincludingtheactualparameternames.ButIlookedinthehelp(asImsure
youdid),andsawthatreferenceObjectispositional,andoccupiesthefirstposition.The
differenceObjectparameterisalsopositional,andoccupiesposition2.Withthesepositional
parameters,IdontneedtotypetheparameternamesolongasIputtheparametervalues
intothecorrectpositions.Thus:
Diff(Ps)(ImportCliXMLbaseline.xml)
Theparenthesesaredoingsomethingspecial.Justlikeinalgebra,theytelltheshellto
executewhateverisinsidetheparenthesesfirst.Theresultofwhateversinsidethe
parenthesesispassedtotheparameter.SotheresultofGetProcess(whichisabunchof
processobjects)ispassedtoreferenceObject,andtheresultofImportCliXML
baseline.xmlispassedtothedifferenceObjectparameter.Basically,Imcomparingtwo
setsofprocesses:thecurrentsetandthesetthatIhadexportedtoaCliXMLfileearlier.

10

PowerShell Crash Course

Don Jones

Theresultsarehorrible.Oops.Thatsactuallybecauseeverythingaboutprocessesis
constantlychanging,includingtheirmemoryuse,CPUuse,andsoon.Iddobettertojust
compareasingle,unchangingpropertylikename:
Diff(Ps)(ImportCliXMLbaseline.xml)propertyName
Ah,therearesomeresults.Icannowseewhichobjectswerepresentintheleftside(the
currentprocesses)butnotintheright(thebaseline).Sothisisadifferencereportofmy
currentconfigurationversusmybaselineconfiguration.Imaginewhatothertypesof
objectsyoucouldexportandcompareinthisfashion!

DownloadAdditionalBooksfromRealtimeNexus!
RealtimeNexusTheDigitalLibraryprovidesworldclassexpertresourcesthatIT
professionalsdependontolearnaboutthenewesttechnologies.Ifyoufoundthisbookto
beinformative,weencourageyoutodownloadmoreofourindustryleadingtechnology
booksandvideoguidesatRealtimeNexus.Pleasevisit
http://nexus.realtimepublishers.com.

11

You might also like