Академический Документы
Профессиональный Документы
Культура Документы
Windows PowerShell v2
Don Jones
PowerShellCrashCourse
DonJones
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
PowerShellCrashCourse
DonJones
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 PowerShellCrashCourseWeek2..................................................................................................................12 Week2,Day1:Variables...............................................................................................................................12 Week2,Day2:OperatorsandFiltering..................................................................................................15 Week2,Day3:Formatting...........................................................................................................................17 Week2,Day4:GettingOut.......................................................................................................................19 Week2,Day5:ExtendingtheShell..........................................................................................................20 WeekendWrapUp..........................................................................................................................................21 . PowerShellCrashCourseWeek3..................................................................................................................22 Week3,Day1:RemoteControl..................................................................................................................23 PreRequisitesandSetup.........................................................................................................................23 1:1Remoting.................................................................................................................................................23 . 1:ManyRemoting.........................................................................................................................................23
ii
PowerShellCrashCourse
DonJones
ReUsingConnections................................................................................................................................25 Week3,Day2:IntheBackground............................................................................................................26 StartingaJob.................................................................................................................................................26 . ManagingJobs...............................................................................................................................................27 GettingResultsfromJobs.........................................................................................................................27 Week3,Day3:ImplicitRemoting.............................................................................................................28 Week3,Day4:MakingaSimpleReusableCommand......................................................................28 Week3,Day5:SELECTing............................................................................................................................29 Week3WrapUp..............................................................................................................................................30 . PowerShellCrashCourseWeek4..................................................................................................................31 Week4,Day1:ErrorHandling...................................................................................................................32 Week4,Day2:DebugTraceMessages...................................................................................................32 Week4,Day3:Breakpoints.........................................................................................................................33 Week4,Day4:WMI........................................................................................................................................34 Week4,Day5:Tools.......................................................................................................................................35 MonthWrapUp................................................................................................................................................36 . DownloadAdditionalBooksfromRealtimeNexus!..........................................................................36
iii
PowerShellCrashCourse
DonJones
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.
iv
PowerShellCrashCourse
DonJones
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.
PowerShellCrashCourse
DonJones
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.
PowerShellCrashCourse
DonJones
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!
PowerShellCrashCourse
DonJones
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.
PowerShellCrashCourse
DonJones
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?
PowerShellCrashCourse
DonJones
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.
PowerShellCrashCourse
DonJones
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.
PowerShellCrashCourse
DonJones
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.
PowerShellCrashCourse
DonJones
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
Themorecomfortableyoubecomereadingthehelp,themorecapabilitiesyoullfind!
PowerShellCrashCourse
DonJones
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
PowerShellCrashCourse
DonJones
11
PowerShellCrashCourse
DonJones
PowerShellCrashCourseWeek2
Hopefully,yourereadyforthesecondweekofyourcrashcourse.Thepreviousfivelessons shouldhaveyoucomfortablyrunningmediumcomplexcommandsfromthecommand line.Thisweek,weregoingtofocusonfinetuningthoseskillsandgivingyousome additionaloptionsandcapabilities. Remember,Iencourageyoutocontinueexploringbeyondthiscrashcourse.Forexample, visithttp://windowsitpro.com/go/DonJonesPowerShelltofindtipsandtricks,FAQs,and toaskquestions,ordropbythePowerShellteamsownblogat http://blogs.msdn.com/powershellforinsiderinformation.Youllalsofindalotofin personPowerShellinstructionateventslikeTechMentor (http://www.techmentorevents.com)andWindowsConnections (http://www.winconnections.com).Finally,yourewelcometosubscribetomyTwitter feed,@concentrateddon.IfocusalmostexclusivelyonPowerShell,andIllpassalongany tipsorarticlesthatIfindespeciallyuseful. HowtoUsethisCrashCourse Isuggestthatyoutackleasinglecrashcourseitemeachday.Spendsome timepracticingwhateverexamplesareprovidedandtryingtocompletetasks thatmakesenseinyourenvironment.Dontbeafraidtofail:Errorsarehow welearn.Justdoitinavirtualenvironment(Irecommendavirtualized domaincontrollerrunningWindowsServer2008R2)sothatyoudontupset theboss!EachDayinthiscrashcourseisdesignedtobereviewedinunder anhour,soitsaperfectwaytospendlunchforafewweeks.Thisbookwill bepublishedinfivedayincrements,soeachchaptercorrespondstoasingle weekoflearning.
Week2,Day1:Variables
Sofar,wevejustbeenrunningcommandsandallowingtheoutputtoshowuponthe screen.Butsometimesyoumightwanttopreservecommandoutputforawhileandreuse it,orevenpersistsomeotherbitofinformation.Thatswherevariablescomein.No,were notgoingtobedoingprogrammingvariablesarejustanamedstorageareainmemory. ThinkofPowerShellsmemoryspaceasawarehouse.Thewarehouseisfullofboxes,and wecanputstuffintotheboxes.Tomakethemeasiertofind,theboxeseachhaveaname. Thoseboxesarevariables.
12
PowerShellCrashCourse
DonJones
Variablenamescanincludealmostanycharacter,includingspaces,althoughyoull probablywanttostickwithletters,numbers,andtheunderscorecharacter.Whenyou wantPowerShelltousethecontentsofavariable,youprecedethevariablesnamewitha$. Thatsaspecialcharacterthatsimplytellstheshell,Hey,whatcomesnextisavariable nameIwantyoutousethecontentsofthatvariable.ForexampleComputermightbea variablename,and$ComputertellsPowerShellthatyouwanttoreferenceitscontents. ${Thisisavariable}isvalid,too.Normally,awhitespaceindicatestheendofthevariable name,butinthiscasethevariablenameThisisavariablecontainsspaces.Surrounding thenameincurlybraceshelpskeepitalltogether.Imnotafanofvariablenamesthat containspacessimplybecausethatsyntaxishardertoread,butyoucandowhateveryou like. ReadThisBitifYoureExperiencedwithVBScript Atthispoint,VBScriptfolksusuallyaskiftheresawaytodeclarevariablesin advance.Yes,thereis.TheresactuallyawholeraftofVariablecmdlets, includingNewVariable,forthatpurpose.Notethatthosecmdletsaccepta nameparameter,whichspecifiesthenameofthevariable.Thevariablename doesnotincludethe$.IfyouranNewVariablename$minevalue7,it wouldattempttocreateanewvariableusingthecontentsof$mineasthe variablename. Thenextquestionisalways:Isthereawaytorequireadvancevariable declaration?Asin,HowdoIdoOptionExplicitinPowerShell?No,there isnt.Youcant.Sorry.Yes,Imawarethatthislackcanmakedebugging harder,butthePowerShellteamhasntimplementedthis.Thereissomething similarreadthehelpforSetStrictModebutitsnotthesameasOption Explicit. Youputstuffintovariablesusingthe=assignmentoperator:
$var=GetServices
Youcanalsoaccessindividualelements.Trythese:
$var[0] $var[1] $var[1] $var[2]
13
PowerShellCrashCourse
DonJones
Nowtrytofigureoutwhat$var2and$var3contain.Betteryet,runthosecommandsinthe shell.Youlllearnafewthings: Youcaneasilychangethecontentsofavariableanytimeyoulike.Justbecauseit startedoutcontainingservicesdoesntmeanitcantswitchtocontainasimple string.Itsjustabox,afterallyoucanreplaceitscontents. Indoublequotes,PowerShelllooksforvariableskeyedbythe$andreplaces themwiththeircontents.Thatdoesnthappeninsinglequotes. WhenyoupipeavariabletoGetMember,youseeinformationaboutwhatevers insidethevariable.Wedontcareabouttheboxitselfweonlycareaboutwhatsin thebox.AskanykidatChristmastimetheyllexplainthatconcepttoyou!
PowerShellstoresallofitsvariablesintheVariabledrive.
DirVariable:
14
PowerShellCrashCourse
DonJones
Week2,Day2:OperatorsandFiltering
PowerShellhastheabilitytocomparebitsofinformationtoeachother.Itdoessousinga setofcomparisonoperators: eq=equality ne=inequality ge=greaterthanorequalto le=lessthanorequalto lt=lessthan gt=greaterthan like=wildcard(use*wildcardcharacter) notlike=oppositeoflike
Hereshowyoumightusethese:
$x=5 $y=10 $xgt$y $yeq$x $a="Hello" $b="HelloWorld" $aeq$b $blike'*Wo*'
15
PowerShellCrashCourse
DonJones
Those{curlybraces}representsomethingcalledascriptblock;inthisinstance,itsactually somethingmorespecific:afilterblock.Youcanputbasicallywhatevercodeyoulikein there,solongasthefinalresultiseitherTrueorFalse.Withinthatblockandonlywithin thatblock,PowerShellisdesignedtolookforaspecial$_placeholder.Thisislikeafillin theblankareaonyourtaxform,andtheshellfillsintheblankwithwhateverwaspiped intoWhereObject.Inthiscase,then,$_representsthattableofserviceinformation. Theperiodtellstheshellthatyoudontwanttodealwiththeentiretablebutinsteadwant toaccesstheinformationinasinglecolumn.Youthenfollowtheperiodwiththecolumn name:Status.SoImcomparingtheStatuscolumntothestringRunning;tablerowsthat matchwillberetained,andonesthatdontwillbedropped.Tryrunningthecommandto seetheresults. Youcandocomplexcomparisons,too:
GetWmiObjectclassWin32_Service|Where{$_.Statene'Running'and $_.StartModeeq'Auto'}
Thisisgrabbing(fromWMI,thistime)alltheservicesthataresettoautostartbutwhich arentyetstarted.Theandoperatorcombinesthetwocomparisons.Therearealsoanor operatorandanotoperatorthatreversethelogic.Keepinmindthat$_isntglobally presentthroughouttheshell:ItsonlyvalidinplaceswherePowerShellisexplicitlylooking forit,andthisisoneofthefewplaceswheretheshelldoesso. Thissyntaxcanbeabitdifficultatfirst,butthisisoneofthemostimportantconceptsinthe shell.Dontproceeduntilyourecomfortablewithit.Topractice,trysomeofthesetasks: GetalistofprocessesthathaveanIDgreaterthan1000 Getalistofeventlogentries(GetEventLogisthecmdlettostartwith)thathavean eventIDgreaterthan1500 Getalistofprocessesthathavesvchostintheirname Getalistofservicesthathavewin*intheirname
16
PowerShellCrashCourse
DonJones
Week2,Day3:Formatting
Sofar,wevebeenhappytousetheformattingthattheshellgivesusbydefault,althoughin thefirstchapterofthisbook,Ididshowyouafewalternativesforformattingoutputas tablesandlists.Now,weneedtojumpinandtakefullcontrol.Thiscangetabitcomplex,so bearwithme.First,knowthatyouhavethreebasicformattingcmdletsthatyoullusemost ofthetime: FormatTable,whichproducesacolumnartable FormatList,whichproducesasimplerlist FormatWide,whichdisplaysasinglepieceofinformationinamulticolumnlist
Youshouldreadthehelponalloftheseforaquickoverviewofwhateachcando.Format Wideisthesimplest:Youcanspecifytheproperty(tablecolumn)youwantdisplayed,and itdefaultstothenamepropertybecausemostobjectshaveaNameproperty.Youcanalso changethenumberofcolumnsdisplayedorspecifyautosizetoletitdisplayasmanyasit thinksitcan.Readthehelpandseeifyoucanfigureouthowtodisplayafourcolumnlistof processnames.Goon,Illwaitforyou. Didyougetit?Well,Imnotgivingawayanyanswers.Again,ifyourestuck,hopon http://connect.concentratedtech.comandIllhelpyouout. FormatListisprobablythenextmostcomplicated.Withit,youcanspecifyalistof propertiestodisplay,andthatlistcanincludewildcards.Forexample,trythese:
GetProcess|FormatList* GetProcess|FormatList*Memory* GetProcess|FormatListName,ID,VM
17
PowerShellCrashCourse
DonJones
Ifyouvesortedyourobjects,youcanhaveFormatTablegroupthem.Eachgroupgetsa newsetofcolumnheaders.Forexample:
GetService|SortStatus|FormatTableName,Statusautosize groupbyStatus
Thathashtablehastwoitems.Theitemsareseparatedbyasemicolon,thewholethingis containedin{curlybraces},andan@signtellstheshellthatweredefiningahashtable. WhenmakingcustomcolumnsinFormatTable,yourenotquitesofreeform.Youhaveto specifyexactlytwokeys:Label(whichcanalsobecalledName),andExpression.Thesecan beshortenedtojustlande,whicharealoteasiertotype.TheLabeliswhatyouwant yourcustomcolumntobetitled,andtheexpressionisascriptblockthatcalculatesthe columnscontent.WithinthatscriptblockjustaswithWhereObject,whichIshowedyou earlierinthischapteryoucanusethe$_placeholdertorefertotheremainderofthe currenttablerow. Heresanexample.Thisisallmeanttobetypedononeline,bytheway.
GetWmiObjectclassWin32_LogicalDiskfilter'DriveType=3'| FormatTableDeviceID,@{l='Size(MB)';e={$_.Size/1MBas[int]}}
18
PowerShellCrashCourse
DonJones
AlthoughIinviteyoutotry.Theresultsmaysurpriseyou.
Week2,Day4:GettingOut
Onceyouveformatteddata,youmightbeinterestedinlookingatit.Bydefault,anything leftinthepipelineatitsendwillbesenttoabuiltin,hardcodedcmdletcalledOutDefault. InthePowerShellconsolehostandISE,OutDefaultsimplyforwardstoOutHost.OutHost isthecmdletresponsibleforputtinginformationonthescreen(hostmeansscreen, here). ThereareotherOutcmdletsyoucanplaywith:OutFileandOutPrinteraretwocommon ones.Together,thesefourOutcmdletshaveonethingincommon:Theyonlyconsumethe outputofaFormatcmdlet.Thatis,ifyourunthis:
GetService
Whatsreallyhappeningunderthehoodlookssomethinglikethis:
GetService|OutDefault|FormatTable|OutHost
Illleaveyouwiththat.ExperimentwithsomeoftheOutcmdletsandseewhatyoucan comeupwith.
19
PowerShellCrashCourse
DonJones
Week2,Day5:ExtendingtheShell
StopthinkingaboutPowerShellforasecondandstartthinkingabouttheMMC.Whenyou openanew,blankMMC,itisntveryuseful,isit?Youhavetoaddsnapinstoitinorderto addactualfunctionality.Youcanaddasmanysnapinsasyoulike,fromwhatever administrativetoolsyouveinstalledonyourcomputer. PowerShellisthesameway.Now,theresabitofconfusiongoingaroundaboutthis.Install theExchangeServeradmintoolsandyoullgetanExchangeManagementShellicon. SharePointdoessomethingsimilar.WindowsServer2008R2hasanActiveDirectory shellicon.ThesearentdifferentversionsofPowerShell.LiketheMMC,thesearejusticons thatloadthesameoldPowerShell,withaparticularextensionpreloaded.Youcanalso loadthosesameextensionsintothenormalshellyourself,andifyouopenoneofthese preloadedshells,youcanstillloadwhateverotherextensionsyoulike.Itsyourchoice. Whenyoudoloadanextension,itonlystaysloadedforthedurationofthatshellsession. Whenyouopenanewshellwindow,yourestartingfromscratch.Abitlater,Illintroduce youtoprofiles,whichgiveyouawaytohavethesameextensionsloadedineverynewshell window.Fornow,youneedtoknowthattherearetwowaysofextendingtheshell: PSSnapins(orsnapins)istheoldschool,v1wayofdoingit.Snapinshavetobe installed(generally,installtheadministrativetoolsforaproductandyoullgetthe snapin).RunGetPSSnapinregisteredtoseewhichonesareinstalled;withthat listofnames,youcanrunAddPSSnapintoloadaparticularsnapinbyname.Youll stillfindnewsnapinsbeingproducedevenWindowsServer2008R2shipped withanewsnapinortwo. Modulesarethenew,v2wayofextendingtheshell.RunGetModulelisttoseea listofwhatsavailableonyourcomputer,andImportModule(alongwiththe modulename)toloadamoduleintomemory.
Imaintainadirectoryofthehigherqualitystuffathttp://ShellHub.com.Dropbyandsee whatticklesyourfancy.
20
PowerShellCrashCourse
DonJones
WeekendWrapUp
Ifyourestickingwiththeonelessonperdayregimen,thenyoureprobablyreadyforthe weekend.Takeacoupleofdaysoff!Thenextinstallmentwillhaveanotherweekoflessons foryou.Untilthen,keeppracticingwhatyouvelearned! Bytheway,ifyougotthischapterasapassalongfromafriend,thanksforreadingit.Hop onhttp://nexus.realtimepublishers.comformorechaptersfromthisbook,andforalotof otherfreebooks.Registrationisrequired,butyoullbeabletodownloadPDFversionsof alltheirbooksatnocharge.Speakingasanauthor,thatsveryimportant:Yourregistration letsthepublisherknowthatyoureinterestedinthisbook,andthatkeepsthepublisher engagingauthorslikemyselftowritemoreforyou.Iappreciateit.
21
PowerShellCrashCourse
DonJones
PowerShellCrashCourseWeek3
Hopefully,yourereadyforweek3ofyourcrashcourse.Theprevioustenlessonshave coveredthemajorityofWindowsPowerShellscoretechniquesandpatterns.Thisweek weregoingtostartlearningaboutsomeofitscoolerembeddedtechnologies,buildingon thosetechniquesandpatterns. Dontforget:Iencourageyoutocontinueexploringbeyondthiscrashcourse,too.For example,visithttp://windowsitpro.com/go/DonJonesPowerShelltofindtipsandtricks andFAQsandtoaskquestions,ordropbythePowerShellteamsownblogat http://blogs.msdn.com/powershellforinsiderinformation.Youllalsofindalotofin personPowerShellinstructionateventslikeTechMentor (http://www.techmentorevents.com)andWindowsConnections (http://www.winconnections.com).IfyouwanttogetafewPowerShelltipsperweek, yourewelcometosubscribetomyTwitterfeed,@concentrateddon.Ifocusalmost exclusivelyonPowerShell,andIllpassalonganytipsorarticlesthatIfindespecially useful.IvealsoputupanewresourcetohelpyoufindalltheothergoodPowerShell resources:http://shellhub.com.Itsahandpickedlistofthingsguaranteedtobeusefuland educational. HowtoUsethisCrashCourse Isuggestthatyoutackleasinglecrashcourseitemeachday.Spendsome timepracticingwhateverexamplesareprovidedandtryingtocomplete tasksthatmakesenseinyourenvironment.Dontbeafraidtofail:Errors arehowwelearn.Justdoitinavirtualenvironment(Irecommenda virtualizeddomaincontrollerrunningWindowsServer2008R2)sothatyou dontupsettheboss!EachDayinthiscrashcourseisdesignedtobe reviewedinunderanhour,soitsaperfectwaytospendlunchforafew weeks.Thisbookwillbepublishedinfivedayincrements,soeachchapter correspondstoasingleweekoflearning.
22
PowerShellCrashCourse
DonJones
Week3,Day1:RemoteControl
OneofthecoolestnewfeaturesinWindowsPowerShellv2isitsbuiltinremoting.Withit, everycommandcanberunononeormoreremotecomputersevensimultaneously withoutthecommandsauthorshavingtodoanyextraworktomakeitpossible.
PreRequisitesandSetup
First,youneedtogetremotingenabled.ItrequiresthatPowerShellv2beinstalledoneach andeverycomputerthatyouwanttoremoteto.ThenrunEnablePSRemotingonthose computerstoturnontheabilitytoreceiveincomingconnections.Youcanalsocontrolthat throughGPO:Runhelpabout_remote_troubleshootingfordetailsonhowtosetthatup andforhelpontopicslikeconnectingnondomaincomputers,remotingacrossaproxy serverorfirewall,andsoon. Authentication,bydefault,isdoneusingKerberossoyourpasswordstayssafe.By default,youllremoteusingwhatevercredentialwasusedtolaunchPowerShellnormally, itllneedtobeanAdministratoraccount.TheserviceinvolvedinremotingisWindows RemoteManagement(WinRM),andtheprotocolisWebServicesforManagement(WS MAN),whichridesatopHTTP.EnablePSRemotingwillsetupthenecessaryexceptionsin theWindowsFirewallforyou.
1:1Remoting
Ifyoujustneedtodosomethingwithonecomputer,thenyoucanremotetoit interactivelykindoflikeSSHinUnix.PowerShelldoesprovideencryption,andyoucan havetheentireconnectionrunoverHTTPS(ratherthanthedefaultHTTP)forgreater security.JustrunEnterPSSessioncomputercomputernametostartasession;youllsee thePowerShellpromptchangeappropriately,andyoullberunningcommandsonthe remotecomputer.Whenyouredone,runExitPSSessiontoreturntoyourlocalprompt andclosetheremoteconnection. EnterPSSessionoffersanumberofoptions.Reviewthehelpandseeifyoucanfigureout howyouwould: AddSSL(HTTPS)totheconnection SpecifyanalternateIPport(usedifyouvechangedtheportthatWinRMlistensto ontheremotemachine) Specifyanalternatecredentialfortheconnection
1:ManyRemoting
Managingonecomputeratatimecanbeuseful,butitsnotautomation.Whatsoftenbetter istheabilitytohavethesamecommandrunonmultiplecomputers,allatonce.Youdothat withInvokeCommand.Heresasimpleexampleusingthreecomputers:
InvokeCommandscriptblock{GetEventLogLogSecuritynewest100} computernameserver1,server2,server3
23
PowerShellCrashCourse
DonJones
Isbetterthanthis:
InvokeCommandscriptblock{ps}computernameserver1,server2,server3| Sortvmdesc|selectfirst10
24
PowerShellCrashCourse
DonJones
ReUsingConnections
Whenyougiveacomputername(orcomputernames)toInvokeCommandorEnter PSSession,thecommandscreateaconnection,thenautomaticallytearitdownwhenyoure donewithit.Thatmeanseverytimeyouopenanewconnection,youmighthavetospecify credentials,alternateports,andotheroptionswhichcanbetedious. Anotheroptionistocreateareusableconnection,calledaPSSession.Whenyoudoso, youllprobablywanttosavethesession(orsessions)inavariablebecausethatmakesit easiertoreuseit.Forexample:
$webservers=NewPSSessioncomputernamewww1,www2,www3 credentialAdministrator
25
PowerShellCrashCourse
DonJones
Whenyourereadytousethesession,justprovideittothesessionparameterofInvoke Command:
InvokeCommandscript{GetProcess}session$webservers
Toclosethesessions:
$webservers|RemovePSSession
Week3,Day2:IntheBackground
Youmayoftenhavetimeswhenyouwanttokickoffsomelongrunningtask,butyoudont wanttowaitforittocomplete.PowerShellprovidesbackgroundjobsasawayofmovinga taskintothebackground,wheretheshellwillcontinuetoexecuteandmonitorit.Theshell willalsocacheanyresultsthatthejobgenerates,enablingyoutoreceivethoseresultsonce youreready.
StartingaJob
Therearethreewaystostartajob: Ifitsalocaltaskthatwontconnecttoremotecomputers,usetheStartJobcmdlet. Giveitacommandparameter,whichtellsitwhatcommandstoruninthe background:
StartJobcommand{GetEventLoglogSecurity}
GetWmiObjecthasanAsJobparameter,whichforcestheWMIprocessingintothe backgroundespeciallyusefulwhendealingwithmanyremotecomputers.
GetWmiObjectclassWin32_BIOScomputerserver1,server2asjob
26
PowerShellCrashCourse
DonJones
InvokeCommandscriptblock{GetEventLoglogSecurity} computernameserver1,server2,server3asjob
ManagingJobs
RunGetJobtoseealistofjobsandtheirstatesRunning,Completed,Failed,andsoforth. NotethateveryjobhasanIDnumber,alongwithaname.Youcangetthestatusfora particularjobbyusingthatIDorname.IliketopipetheresultstoFormatListsothatIcan seeallofthejobsdetails:
GetJobnameMyJob|FormatListproperty*
Whenyouredonewithajob,youcanremoveittocleanupthelist:
GetJobnameMyOldJob|RemoveJob
TheresalsoStopJob,tokillastuckjob,andWaitJob,whichisusefulwhenascriptneeds tostartajobandthenwaituntilitcompletesbeforerunningmorecommands.
GettingResultsfromJobs
Whenajobisfinished,itlllikelyhavesomeresultsforyou.Hereshowtogetthem:
ReceiveJobid4
Or
ReceiveJobnameMyDoneJob
27
PowerShellCrashCourse
DonJones
Week3,Day3:ImplicitRemoting
Microsofthasalwayshadversioningchallenges.Forexample,WindowsServer2008R2 shipswithanewActiveDirectorymoduleformanagingADbutthatmodulecanonlyrun on2008R2andWindows7.WhatifyourestuckonXP?Implicitremotingisdesignedto helpsolvetheproblem. Heresthescenario:Youhavea2008R2domaincontroller,whichhastheActiveDirectory modulealreadyinstalled(itcomesalongwiththedomaincontrollerrole).Youenable remoting(EnablePSRemoting)onthatdomaincontroller,thensettledowninfrontofyour WindowsXPmachinethathasPowerShellv2installed.Runthesecommands,assuming DC2008isthenameofthatdomaincontroller:
$session=NewPSSessioncomputernameDC2008 InvokeCommandscript{ImportModuleActiveDirectory}session$session ImportPSSessionsession$sessionmoduleActiveDirectoryprefixRem
Week3,Day4:MakingaSimpleReusableCommand
Letssayyouvecreatedareallykickbuttcommandthataccomplishedsomegreatstuff.Its alotoftyping,butyoulovethewayitworks:
GetWmiObjectclassWin32_LogicalDiskfilter"DriveType=3" computernameserver1,server2,server3|SelectObjectDeviceID, @{n='ComputerName';e={$_.__SERVER}}, @{n='Size(GB)';e={$_.Size/1GBas[int]}}, @{n='FreeSpace(MB)';e={$_.FreeSapce/1MBas[int]}}
28
PowerShellCrashCourse
DonJones
ThatleadingdotwillloadthecontentsofUtilities.ps1intotheshellsglobalscope,making yourcommandavailablejustlikeanyother.Touseit:
GetDriveInventorycompserverr2
Theshellevensupportsabbreviatingthecomputernameparameter,asshownhere.Neat, right?
Week3,Day5:SELECTing
TheexamplefromtheprevioussectionutilizedalittleknownfeatureoftheSelectObject cmdlet.Thiscommandhasfourreallyusefulfeatures: Youcantellitwhatpropertiesyouwanttokeepforanobject,helpingtowhittle downoutputtoexactlywhatyouwanttosee:
GetProcess|SelectpropertyID,Responding,VM,PM
29
PowerShellCrashCourse
DonJones
Youcanalsoselectasubsetoftheobjectspipedingrabbingthefirstorlast howevermany:
GetService|Selectfirst10
GetADComputerfilter*|SelectexpandName
Givethesetechniquesatrywithvariousothercommandsandseewhathappens.
Week3WrapUp
Thisweek,youvelearnedaboutpowerfulembeddedtechnologieswithinPowerShelland youvealsolearnedsomenewpatterns.Forexample,thevariouswaysinwhichIshowed youtofeedcomputernamestothecomputernameparameterofInvokeCommandareall patternsyoullfindusesforwithmanyothercmdlets.Payattentiontothesedifferent patterns,andtrytothinkofwaysinwhichyoumightusethemelsewherewithintheshell. Illleaveyouwithafinalsupercomplexexample.Lookthroughthiscarefully,andseeifyou canfigureoutwhyitdoeswhatitdoes.Thisissafetorunonaproductionsystemoryour workstation,too,sothatyoucanseetheresults.Howwouldyoumodifythistorunagainst aremotecomputer?
GetWmiObjectclassWin32_OperatingSystem|SelectObject @{n='OSVersion';e={$_.Caption}}, @{n='SPVersion';e={$_.ServicePackMajorVersion}}, @{n='OSBuild';e={$_.BuildNumber}}, @{n='ComputerName';e={$_.__SERVER}}, @{n='BIOSSerial';e={ (GetWmiObjectclassWin32_BIOScomputername$_.__SERVER| SelectExpandSerialNumber) }}|FormatTableproperty*wrap
Goodluck!
30
PowerShellCrashCourse
DonJones
PowerShellCrashCourseWeek4
Welcometothelastweekofourcrashcourse!Theprevious15lessonshavecoveredthe majorityofWindowsPowerShellsmainfunctionality.Wellcontinuebuildingthisweek, coveringintermediatetechniquesthatmayprovehelpfulfromtimetotime. Dontforget:Iencourageyoutocontinueexploringbeyondthiscrashcourse,too.For example,visithttp://windowsitpro.com/go/DonJonesPowerShelltofindtipsandtricks andFAQsandtoaskquestions,ordropbythePowerShellteamsownblogat http://blogs.msdn.com/powershellforinsiderinformation.Youllalsofindalotofin personPowerShellinstructionateventslikeTechMentor (http://www.techmentorevents.com)andWindowsConnections (http://www.winconnections.com).IfyouwanttogetafewPowerShelltipsperweek, yourewelcometosubscribetomyTwitterfeed,@concentrateddon.Ifocusalmost exclusivelyonPowerShell,andIllpassalonganytipsorarticlesthatIfindespecially useful.IvealsoputupanewresourcetohelpyoufindalltheothergoodPowerShell resources:http://shellhub.com.Itsahandpickedlistofthingsguaranteedtobeusefuland educational. HowtoUsethisCrashCourse Isuggestthatyoutackleasinglecrashcourseitemeachday.Spendsome timepracticingwhateverexamplesareprovidedandtryingtocomplete tasksthatmakesenseinyourenvironment.Dontbeafraidtofail:Errors arehowwelearn.Justdoitinavirtualenvironment(Irecommenda virtualizeddomaincontrollerrunningWindowsServer2008R2)sothatyou dontupsettheboss!EachDayinthiscrashcourseisdesignedtobe reviewedinunderanhour,soitsaperfectwaytospendlunchforafew weeks.Thisbookwillbepublishedinfivedayincrements,soeachchapter correspondstoasingleweekoflearning.
31
PowerShellCrashCourse
DonJones
Week4,Day1:ErrorHandling
Errorsareinevitable.Someofthem,however,youcananticipatethingslikeacomputer notbeingavailableonthenetworkorapermissionbeingdenied.Dontlistentothe Internetsandjustset$ErrorActionPreference=SilentlyContinueatthetopofascript: Thatsagoodwaytosuppressusefulerrormessagesthatyoudidntanticipate.Instead, locatecommandsthatyouthinkmightcauseanerror,andaddtheparameterEAStopto them.Then,wrapthecommandinaTryCatchblock:
Try{ GetServicecomputer$computernameeaStop }Catch{ "Couldnotreach$computername"|OutFilelog.txtappend }
Week4,Day2:DebugTraceMessages
Sometimesyoumighthaveacomplicatedscriptthatjustisntdoingwhatyouexpectitto. 99%ofthetime,Ifindthatthoseproblemscomedirectlyfromapropertyvalue,ora variable,thatcontainsavalueotherthanwhatyouexpected.Forexample,Ioncewrotea scriptlikethis:
$result=TestConnection$computername if($result){ GetServicecomputername$computername }
Iwastryingtopingthecomputerbeforeattemptingtoconnecttoit,butthiscodenever worked.SoIaddedsomedebugcode:
$DebugPreference="Continue" $result=TestConnection$computername WriteDebug$result if($result){ WriteDebug"Tryingtoconnect" GetServicecomputername$computername }else{ WriteDebug"Nottryingtoconnect" }
32
PowerShellCrashCourse
DonJones
Week4,Day3:Breakpoints
Inalongscript,youcouldeasilywindupscanningthroughhundredsoflinesofdebug output.Yuck.Analternativeistojustletthescriptruntothepointwhereyouthinktheres aproblem,thenletthescriptpausesothatyoucanmanuallyexaminevariables,properties, andwhatnot.Youcandothiswithabreakpoint. Youbasicallysetabreakpointforyourscriptbygivingyourscriptspathandfilename. Thenyoucandecideifthescriptisgoingtobreakwhenyouhitaparticularlineinthe script,whenaparticularvariableisreadorwritten,orwhenaparticularcommandis executed.ItsalldonewiththeSetPSBreakpointcmdlet:
SetPSBreakpointscriptc:\mine.ps1line37
Andyouredone.Thisisasetoftechniquesthattakesaweebitofpracticetogetusedto, butitsapowerfulandusefultechniqueonceyoudo.
33
PowerShellCrashCourse
DonJones
Week4,Day4:WMI
IcantbelieveIletyougoallthewaytothelastweek,onthenexttothelastday,tocover WindowsManagementInstrumentation!AWMIcrashcourseisdefinitelyinorderhere. WMIisatechnologythatsbeenincludedinWindowssinceWindows2000anditseven anaddinfeatureforWindowsNT4.0,ifyoustillhaveanyofthatlyingaround.Microsoft expandsitabitineachnewversion,andmanyproductslikeOffice,SQLServer,andso forthcanallextendWMIaswell.Atitscore,WMIisprimarilyaboutquerying managementinformation;therearesomeopportunitiestomakeconfigurationchanges,but theyreabitrare,andImnotgoingtodiveintotheminthislittlecrashcourse. WMIisorganizedintonamespaces,withtheroot\v2namespacebeingthedefault.The namespacescontainclasses,andthoseclassesrepresentthemanageablecomponentsthat youcangatherinformationfrom.Aninstanceofaclassactuallyrepresentsanexisting component.So,ifyouhavetwodisks,thenyouhavetwoinstancesofthe Win32_LogicalDiskclass.Toqueryaclass,youjustneedtoknowthecomputeritsonand theclassname(andthenamespace,iftheclassisntinthedefaultnamespace).Whatyou getbackisanobject,justliketheobjectsproducedbyanyPowerShellcmdlet.Youcanpipe themtoGetMembertoseetheirproperties,andthosepropertiescontainthemanagement informationyoureafter:
GetWmiObjectclassWin32_OperatingSystemcomputerlocalhost
Again,neattrick.AddasearchBaseparametertoGetADComputertohaveitstartina specificOUratherthanattherootofthedomain.
34
PowerShellCrashCourse
DonJones
WMIoutputcanbeformatted,exported,andconverted,justliketheoutputofeveryother commandyouveworkedwith.ThetrickwithWMIisinfindingtherightclassforwhatyou want,andsadlytheresnogoodwaytodoit.AWMIExplorerorBrowserhelps(Ill mentiononeinthenextsection),andGoogleis,ofcourse,yourfriend.Googleisalsoagood waytolocatewhatWMIdocumentationisoutthere:PunchaWMIclassnameintoyour searchengineandthefirstcoupleofhitswilllikelybetoMicrosoftsMSDNLibrarysite, wheretheWMIdocumentationthatdoesexistiskept.Dontexpecttofinddocumentation foreveryWMIclassMicrosoftjusthasntbeenconsistentaboutdocumentingthem, unfortunately. Overthelongterm,adminsmayfindthemselvesdealingdirectlywithWMIlessandless,as Microsoftmovesadminfunctionalityintomoreconsistent,betterdocumentedcmdlets. Untilthen,WMIremainsyourbestbet,inmanycases,forretrievingmanagement information.
Week4,Day5:Tools
IdontthinkanyonecanbemaximallysuccessfulatWindowsPowerShellwithoutafew goodsupplementarytools.Herearesomeofmyfavorites: APowerShellHelpviewer,suchasthefreeoneat http://www.primaltools.com/downloads/communitytools/,makesiteasierto browseandreadhelpwhiletypingcommandsinanotherwindow. AWMIExplorer(http://www.primaltools.com/downloads/communitytools/ again)makesiteasiertofindWMIclassesandtoseethepropertiesandmethods theyoffer. WanttobuildgraphicaldialogboxesintoyourPowerShellscripts?Consider PrimalForms(http://www.primaltools.com/products/),acommercialproductthat letsyoudraganddropaGUI,andproducesthescriptneededtomakethatGUIa reality. Youneedabettereditorifyouregoingtogetintoscripting.Trythese: o http://PrimalScript.comisamature,featurerichenvironment.Astudio editionincludestheGUIbuildertoolImentionedearlier. o http://PowerShellPlus.comisaPowerShellonlyeditorthatincorporatesa beefedupcommandlineexperienceinadditiontoscriptediting. o http://PowerGUI.orgoffersafreeeditingexperiencethathelpswritescripts foryou;aproversion(http://quest.com/powerguipro)includesoptionsfor runningPowerShellscriptsfromyourmobiledevice. Youllfindmoreonhttp://ShellHub.com.Allofthesecommercialtoolsofferfreetrial editions,sotheresnoreasonnottotrythemoutandseewhichonesuitsyoubest.
35
PowerShellCrashCourse
DonJones
MonthWrapUp
Wevecoveredalotofground:PowerShellscorecommandsandfunctionality,building customizedtableoutput,debugging,errorhandling,sorting,remotecontrol,background jobs,andtonsmoreallinaveryshortspanoftime.Thebestwaytomakeitallmake senseistodiginthereandstarttryingsomeofthesetechniques.Youllprobablygetstuck atsomepointaskforhelp!Youcanhoponhttp://connect.ConcentratedTech.comand registertoaskmeaquestiondirectly(whenaskedwhereyoutookaclasswithme,justput RealtimePublishers).IalsoencourageyoutofollowmeonTwitter@concentrateddon.My tweetsarealmostexclusivelyaboutnewlypostedPowerShelltipsandcontent,articlesand videos,andmore.And,dontforgetaboutalltheothergreatfreebooksonofferat http://nexus.realtimepublishers.com!
DownloadAdditionalBooksfromRealtimeNexus!
RealtimeNexusTheDigitalLibraryprovidesworldclassexpertresourcesthatIT professionalsdependontolearnaboutthenewesttechnologies.Ifyoufoundthisbookto beinformative,weencourageyoutodownloadmoreofourindustryleadingtechnology booksandvideoguidesatRealtimeNexus.Pleasevisit http://nexus.realtimepublishers.com.
36