Вы находитесь на странице: 1из 41

The Administrator Crash Course

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

[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.

PowerShellCrashCourse

DonJones

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.

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

Nowsthetimeforthatindependentresearch.Howwouldyou: ChangethesortorderofSorttobedescendinginsteadofascending(whichisthe default)? Getthelast20objectsfromthepipelineusingSelect? ChangethedelimiterofaCSVfiletoapipe|characterinsteadofacomma? Displaynotonlytheaveragevalueforprocessingphysicalmemorybutalsothe minimumandmaximumvaluesandthetotalphysicalmemoryused?

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

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!

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

Youdontneedtocreatethevariableinadvance;thefirsttimeyouuseit,PowerShellwill createit.Thepreviouscommandretrievesalltheserviceobjectsandstickstheminto$var. Technically,$varisnowanarray,orcollection(inPowerShell,theyreclosetobeingthe samething).Ifyouwanttodisplaythem,justtelltheshelltodisplaythevariable:


$var

Youcanalsoaccessindividualelements.Trythese:
$var[0] $var[1] $var[1] $var[2]

13

PowerShellCrashCourse

DonJones

Thesquarebracketscontainthezerobasedindexnumberoftheelementyouwantoutof thecollection;negativenumbersstartattheendofthecollection.Goon,tryit.Youllsee. Variablescanalsostoresimplevalueslikestringsandnumbersalthoughtheseare, technically,alsoobjects.


$var=5 $var='Hello' $var2="$varWorld" $var3='$varWorld' $var|GetMember

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:

YoullseealotofthebuiltinvariablesthatcontrolPowerShellsoperationandbehavior, too.YoucandeletevariablesbyusingtheDelcommandrightinthatdrive,ortheRemove Variablecmdlet.Variablesdontpersistbetweenshellsessions,andthebuiltinvariables (whichcanbedeleted,ifyouwant)alwaysreturnwiththeirdefaultvalueswhenyouopen anewshellwindow. PowerShellkeepstrackofwhatkindofobjectorobjectsavariablecontains,butitdoesnt normallyenforceanyrulesaroundthem.Inotherwords,thisisvalid:


$x=5 $x="Realtime"

Youcanstartoutwithonetypeofthing(aninteger,inthiscase)inthebox,thenreplaceit withsomethingelse(astring).Youcan,however,tellPowerShellwhattypeofdatayou wantavariabletocontain.Onceyoudoso,PowerShellwillenforceit.Trythis:


[int]$x=5 $x='Hello'

14

PowerShellCrashCourse

DonJones

Yougetanerroronthesecondlinebecause$xcannowonlycontainan[int]andtheresno waytoconvertHellointoaninteger.Othervariabletypesinclude[string],[xml], [Boolean],[double],andsoon. Finally,variablenameslikecmdletnamesarentcasesensitive.$Xand$xarethesame thing.

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*'

Notethatstringcomparisonsarecaseinsensitive;useceq,clike,andcnotlikeforcase sensitivecomparisons. Onewaytousethesecomparisonoperatorsisinfilteringitemsoutofthepipeline.Lets quicklyrevisithowthisallworks.Imgoingtousesomedifferentterminologythaninthe previouschapter,andthisterminologyglossesoversometechnicalfinedetails,butIthink itmakesthebasicconceptalotclearer.

15

PowerShellCrashCourse

DonJones

WhenyourunacommandlikeGetService,itproducesatableofinformation.Thanksto someformattingdefaultsprovidedbyMicrosoft,however,youonlyseeaportionofthis tableonthescreen.Toseeallofitspossiblecolumns,pipethetabletoGetMember:


GetService|GetMember

AnythinginthatoutputthatsaysProperty,includingthingslikeNotePropertyand AliasProperty,aretablecolumns.Youcanusethosecolumnnames,alongwith comparisonoperators,tofilteritemsoutofthepipeline.UsetheWhereObjectcmdlet(or itsalias,Where)todoso:


GetService|Where{$_.Statuseq'Running'}

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

Onceyoucanaccomplishthosetasks,youregoodtogo.Ifyougetstuck,dropby http://connect.concentratedtech.comwhereyoucanpostaquestiondirectlytome.When youregister,youllbeaskedwhereyoutookaclasswithmeenterRealtimePublishers forthatfield.

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

Gettheidea? FormatTableisthemostfun.SomeoftheoptionsImgoingtoexplorealsoexistfor FormatList,butIthinktheyremoreimpressivewhenusedwithFormatTable. First,beawarethatFormatTablenormallytriestofillyourentirescreenwithtext,edgeto edge,evenifthatmeansputtingalotofspaceinthemiddle.Youcan,however,tellittotry andautomaticallysizeeachtablecolumnforwhateverthatcolumnneedstocontain.Notice thedifferenceinthese:


GetService|FormatTableName,Status GetService|FormatTableName,Statusautosize

17

PowerShellCrashCourse

DonJones

Ifyouvesortedyourobjects,youcanhaveFormatTablegroupthem.Eachgroupgetsa newsetofcolumnheaders.Forexample:
GetService|SortStatus|FormatTableName,Statusautosize groupbyStatus

Neat,right? Youcanalsocreatecustomcolumns.Thesemightsimplytranslateonekindofvalueto another.Forexample,theWin32_LogicalDiskclassincludesaSizepropertythatcontainsa diskssizeinbytes;wecouldmakethatmegabytesinouroutputbyaddingacustom column.Thesyntaxfordoingsoisabitcomplicated,though.Youneedtocreatesomething calledahashtable.Thesearealsoknownasdictionaryobjects.Theycancontainmultiple entries,andeachentryconsistsofakeyandavalue(or,asIliketothinkofthem,aword andadefinition).Makingonelookslikethis:


@{'Key'='Value';'Word'='Definition'}

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]}}

Yeah,Iknowcomplicated.Toldyouso.Focusonthathashtable:Ivesetalabelof Size(MB),whichisstraightforwardenough.Theexpression(e)goesintoa{scriptblock} ratherthaninquotationmarks.Withinthatscriptblockandonlywithinthatscript blockyoucanusethat$_placeholdertorefertotherowofinformation.Followitwitha period,thenthepieceofinformationyouwantSize.Idividedby1MB(yup,PowerShell recognizesKB,MB,GB,TB,andPB).Iusedtheasoperatortoconverttheresulttoan[int] (integer),forcingittodropthefractionalportionoftheresultsothatIgetawholenumber. Illleaveyouwiththat.Playwithit,practicewithit.Hitmeupon http://connect.concentratedtech.comifyougetstuck.

18

PowerShellCrashCourse

DonJones

Onecaution:TheoutputofaFormatcmdletisveryspecialized,anditcanonlybeusedby someveryspecificPowerShellcmdlets,whichIlldiscussnext.Inshort,theFormatcmdlet generallyneedstobethelastthingonthecommandline.Youcantdothis:


GetService|FormatTable|ConvertToHTML>services.html

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

Thatsnotexactlywhatshappening,butitsanillustration.Anyway,Itoldyouearlierthata Formatcmdlet,ifused,needstobethelastthingonthecommandline.Theonlyexception isthataFormatcmdletcanbefollowedbyOutHost,OutPrinter,orOutFile.Infact,these twocommandsareidenticalbecause>isjustanalias(sortof)toOutFile:


Dir>files.txt Dir|OutFilefiles.txt

ReadthehelpforOutFile,bytheway.Youllfindanumberofreallyusefuloptions. TheresalsoOutGridView,whichonlyworksifyouhavethePowerShellISEand.NET Framework3.5installed.Trythis:


GetProcess|OutGridView

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.

Onceyouveloadedanextension,youcanasktheshelltoshowyouwhatwasadded: RunGetCommandpssnapinnametoseethecommandsaddedbythePSSnapin youspecified;replacenamewiththesnapinsactualname. RunGetCommandmodulenametoseethecommandsaddedbythemoduleyou specified.

TheWindows7RemoteServerAdministrationToolkit(RSAT)addsabunchofmodules, andWindows7shipswithafewpreinstalled.WindowsServer2008R2installsmodules alongwiththeirassociatedroles,soadomaincontrollerwillhavetheActiveDirectory module.Thirdpartiescanalsoproducemodulesandsnapins: Quest.com/PowerShellalternateADcmdlets CodePlex.com/powershellcxopensourcecommunityextensions

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

Theresalotofwaystogetcomputernamesintothecomputernameparameter.WhatIdid isprovideacommaseparatedlist,whichPowerShellseesasanarrayofitems.Another wayistoreadnamesfromatextfile,whichcontainsonenameperline:


...computername(getcontentnames.txt)

TheparenthesesforcetheshelltoexecutetheGetContentcommandfirst,thenfeedsits outputtotheparameter.Parenthesesareausefultrick,andthereareseveralwaysin whichyoucanusethem.PerhapsyouhaveaCSVfilethatcontainsacolumnnamedServer? Hereshowyoudusethatcolumn:


...computername(importcsvservers.csv|selectexpandServer)

TheexpandparameterofSelectObjecttellsthecommandtograbthecontentsofthe propertydesignatedinthiscase,theServercolumnofyourCSV,andfeedjustthose valuesasthecommandoutput.Thatgetsstuckontothecomputernameparameter,and voila!YoucanusethesametricktoquerycomputersfromActiveDirectory(AD),assuming youveloadedtheActiveDirectorymodule:


...computername(getadcomputerfilter* searchbase"ou=servers,dc=mycompany,dc=local"|selectexpandName)

ThescriptblockparameterofInvokeCommandiswhereyouputthecommandsyouwant torunremotely;multiplecommandscanbeseparatedbya;semicolon.Youcanfeedin anentirepipeline,andyoushouldhaveasmuchprocessingdoneremotelyaspossible.For example,this:


InvokeCommandscriptblock{ps|sortvmdesc|selectfirst10} computernameserver1,server2,server3

Isbetterthanthis:
InvokeCommandscriptblock{ps}computernameserver1,server2,server3| Sortvmdesc|selectfirst10

Thesecondexamplehasfartoomuchdatabeingtransmittedfromtheremotemachines anditwontproducethesameresults,anyway.Seeifyoucanfigureoutwhy(ifnot,drop byhttp://connect.concentratedtech.comandaskIllbehappytogiveyouaclue.Ifyoure registeringforthefirsttime,enterRealtimeastheplacewhereyoutookaclassfromme andIllmakesureyourregistrationisapproved).

24

PowerShellCrashCourse

DonJones

Bydefault,InvokeCommandtalkstoasmanyas32computersatonce.Giveitmorethan that,andtheextrasgetqueuedupandcompletedinorder.Youcanchangethatwiththe Throttleparameter.Otherparametersyoushouldlookfor(readthehelpnohintsfrom me!): Howtospecifyanalternatecredential HowtospecifyanalternateIPport HowtoenableSSL(HTTPS)fortheconnections Howtospecifyascriptfilepathinsteadofanindividualcommand

Notice,too,thattheresultsofInvokeCommandhaveanextrapropertyattached.The PSComputerNamepropertycontainsthenamethateachresultcamefromsothatyoucan keeptrackofthem.Youcouldsortandgroupthatoutputbycomputernameoncethe outputisbacktoyourcomputer:


InvokeCommandscriptblock{Dirc:\}computername(gcnames.txt)| Sortpscomputername|formattablegroupbypscomputername

Also,keepinmindthatyoucanonlyinvokecommandsthatareavailableontheremote computer.LetssayalloftheremotecomputersareWindowsServer2008R2machines, andyouwanttoseewhatBestPracticesAnalyzer(BPA)modelsareavailableoneach.To dothat,eachremotecomputerneedstoloadtheBestPracticesmodule:


InvokeCommandscriptblock{ImportModuleBestPractices;GetBPAModel} computernameserver1,server2,server3

Thatwouldloadthemoduleoneach,thenexecuteacommandfromthatmodule.Whenthe commandfinishesexecuting,theconnectionwillcloseandthemodulewillunload automatically.

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

EnterPSSessiononlyworkswithasinglecomputer,soyoucanuseanindexnumberto specifywhichofthosesessionsyouwant.Forexample,thesecondsession(www2)would be:


EnterPSSessionsession$webservers[1]

Toclosethesessions:
$webservers|RemovePSSession

Thatalsohappensautomaticallywhenyoucloseyourshell.Leavingasessionopendoes occupysomeprocessorandmemoryoverheadonbothyourmachineandtheremoteone, butitsnotamassiveamount.Justdontgeteveryadmininthehabitofholdingabunchof sessionsopen,andyoullbefine.

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

InvokeCommandalsohasanAsJobparameter,whichforcesittoinvokecommands inthebackgroundagain,usefulwhenyourerunningagainstmultipleremote computers:

InvokeCommandscriptblock{GetEventLoglogSecurity} computernameserver1,server2,server3asjob

Bydefault,youllcreateajobwithagenericnamelikeJob1.BothStartJobandInvoke Commandprovideparameters(nameandjobname,respectively)thatletyouspecifya customjobnameoftenmakingiteasiertomanagemultiplejobs.

ManagingJobs
RunGetJobtoseealistofjobsandtheirstatesRunning,Completed,Failed,andsoforth. NotethateveryjobhasanIDnumber,alongwithaname.Youcangetthestatusfora particularjobbyusingthatIDorname.IliketopipetheresultstoFormatListsothatIcan seeallofthejobsdetails:
GetJobnameMyJob|FormatListproperty*

Akeythingtoknowisthattheshellalwayscreatesaparentjob,plusonechildjobfor eachcomputer.SoajobcreatedbyusingStartJobwillhaveaparentandonechildwhich isthelocalcomputer.AnInvokeCommandjobtargetingfourcomputerswillhavethe parentjobandfourchildren.TheFormatListtrickwillallowyoutoseethenamesofeach childjobenablingyoutogetthosejobsindividually:


GetJobnameJob2|FormatListproperty*

Whenyouredonewithajob,youcanremoveittocleanupthelist:
GetJobnameMyOldJob|RemoveJob

TheresalsoStopJob,tokillastuckjob,andWaitJob,whichisusefulwhenascriptneeds tostartajobandthenwaituntilitcompletesbeforerunningmorecommands.

GettingResultsfromJobs
Whenajobisfinished,itlllikelyhavesomeresultsforyou.Hereshowtogetthem:
ReceiveJobid4

Or
ReceiveJobnameMyDoneJob

Bydefault,thereceivedresultsaredeliveredtoyouandthennolongercachedmeaning youcantreceivethemagain.Ifyouwanttoleavethemcachedinmemory,addtheKeep parametertoReceiveJob.

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

Now,allofthecommandsintheActiveDirectorymoduleareavailableaslocalcommands onyourWindowsXPmachine.Aprefix,Rem,hasbeenaddedtoeachcommandsnoun, helpingremindyouthatthecommandswillactuallyexecuteremotely.Youcanevenaskfor helponthem.Forexample,allofthesewillnowrunfine:


GetRemADUserfilter* HelpNewRemADUser

Neattrick,right?Theideaisthattheserverprovidingthefunctionalitycannowalso providetheadministrativecapability,andyoudontneedtoinstalleverysingleadmintool locallyonyourcomputer.Thisalsohelpsmitigateversionmismatchesbynotcaringwhat OSyourerunningonyourworkstationtoolssimplyrunontheserver.

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

Youwanttosharethatwithsomeothertechsinyourorganization,butyoudontwant themtohavetoretypeallthatorevenedititbecauseyouknowtheyllmessup something.Noproblem.Putthisintoatextfilewitha.ps1filenameextension:


FunctionGetDriveInventory{ Param($computername) GetWmiObjectclassWin32_LogicalDiskfilter"DriveType=3" computername$computername|SelectObjectDeviceID, @{n='ComputerName';e={$_.__SERVER}}, @{n='Size(GB)';e={$_.Size/1GBas[int]}}, @{n='FreeSpace(MB)';e={$_.FreeSapce/1MBas[int]}} }

ThethreelinesinboldfacearewhatIadded,alongwiththeboldfaced$computernamein thecommanditself.Letssayyouputthisinafilenamedc:\scripts\utilities.ps1.Yourother adminfriendscouldthenaddthefollowingtotheirPowerShellprofile(runhelp about_profilesformoreinfo):


.c:\scripts\utilities

ThatleadingdotwillloadthecontentsofUtilities.ps1intotheshellsglobalscope,making yourcommandavailablejustlikeanyother.Touseit:
GetDriveInventorycompserverr2

Theshellevensupportsabbreviatingthecomputernameparameter,asshownhere.Neat, right?

Week3,Day5:SELECTing
TheexamplefromtheprevioussectionutilizedalittleknownfeatureoftheSelectObject cmdlet.Thiscommandhasfourreallyusefulfeatures: Youcantellitwhatpropertiesyouwanttokeepforanobject,helpingtowhittle downoutputtoexactlywhatyouwanttosee:

GetProcess|SelectpropertyID,Responding,VM,PM

Youcanaddcustomproperties,usingahashtablejustlikeyoudidwithFormat TableinChapter2.Thehashtableneedstwokeys:Nisthenameofthenew property,andEistheexpressionusedtocreatethenewpropertysvalues:

GetWmiObjectclassWin32_LogicalDiskfilter"DriveType=3" computernameserver1,server2,server3|SelectObjectpropertyDeviceID, @{n='ComputerName';e={$_.__SERVER}}, @{n='Size(GB)';e={$_.Size/1GBas[int]}}, @{n='FreeSpace(MB)';e={$_.FreeSapce/1MBas[int]}}

29

PowerShellCrashCourse

DonJones

Youcanalsoselectasubsetoftheobjectspipedingrabbingthefirstorlast howevermany:

GetService|Selectfirst10

Youcantellittojustgrabthevaluesfromagivenproperty.Thisforcesthe commandtooutputsimplevaluesinsteadofamorecomplexobjectwithoneor moreproperties:

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 }

Thatsthesmartwaytodealwitherrors.Inthisexample,Imloggingthefailedcomputer nametoafile(withindoublequotes,PowerShellwillreplacethe$computernamevariable withitscontentscooltrick,right?)

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" }

NoticethatIenableddebugoutputonthefirstline,andaddedanElsetomyconstructso thatIdgetsomekindofoutputeitherway.WriteDebugisneatinthatyoucanset $DebugPreference=SilentlyContinueanditllshutoffthedebugoutputwithoutyou havingtogomanuallyripoutalltheWriteDebugcommandsyouadded.

32

PowerShellCrashCourse

DonJones

Thisdidntsolvemyproblem,butitdidmakemerealizethatTestConnectionwasnt returningaTrueoraFalsebutratheracollectionofobjects.Ireadthehelponthecmdlet (shouldhavedonethattostartwith,Iguess),andfoundthechangeIneededtomake:


$DebugPreference="Continue" $result=TestConnection$computernamecount1quiet WriteDebug"Pingis$result" if($result){ WriteDebug"Tryingtoconnect" GetServicecomputername$computername }else{ WriteDebug"Nottryingtoconnect" }

Huzzah!MyproblemcamefromthefactthatIwasexpecting$resulttocontainonething, butitactuallycontainedsomethingquitedifferent.Gettinginsightintotheactualcontents ofthevariablepointedmeinthedirectionofmysolution.Thatswhatdebuggingisall about:gettinginsideyourscriptshead.

Week4,Day3:Breakpoints
Inalongscript,youcouldeasilywindupscanningthroughhundredsoflinesofdebug output.Yuck.Analternativeistojustletthescriptruntothepointwhereyouthinktheres aproblem,thenletthescriptpausesothatyoucanmanuallyexaminevariables,properties, andwhatnot.Youcandothiswithabreakpoint. Youbasicallysetabreakpointforyourscriptbygivingyourscriptspathandfilename. Thenyoucandecideifthescriptisgoingtobreakwhenyouhitaparticularlineinthe script,whenaparticularvariableisreadorwritten,orwhenaparticularcommandis executed.ItsalldonewiththeSetPSBreakpointcmdlet:
SetPSBreakpointscriptc:\mine.ps1line37

Breakpointstakeeffectimmediately,sogoaheadandrunyourscript.Whenyoudo,youll getaveryspecialpromptwhenthescripthitsthebreakpoint.Withinthatprompt,youcan examinevariablesbyjustenteringthevariablename.Whenyouredonelookingaround, runExittoletthescriptresumeexecuting. Whenyourefinishedwithyourbreakpoints,youcandeletethemall:


GetPSBreakpoint|RemovePSBreakpoint

Andyouredone.Thisisasetoftechniquesthattakesaweebitofpracticetogetusedto, butitsapowerfulandusefultechniqueonceyoudo.

33

PowerShellCrashCourse

DonJones

Note AlotofthirdpartyPowerShelltoolsprovidetheirownbreakpoint functionality,andtheyreoftenmuchenhancedoverthebasiccapability. Theylllistoutvariablesforyou,letyouvisuallymanagebreakpoints,andso forth.Illcoversometoolsinthelastlesson.

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

Technically,youdontneedthecomputerparameterifyouwanttoquerythelocalhost.If yourequeryingaremotecomputer,youhavetheadditionaloptionofspecifyinga credentialparameter,whereyoucanprovideanAdministratorusernameiftheaccount youusedtoopenPowerShellisntanadminontheremotemachine.Thecomputername parametercanevenacceptacommaseparatedlistofcomputernames,anditllcontact themsequentially(andskipoveranyonesthatarentavailable).Allgoodtricks. IfyouhavetheActiveDirectorymodulethatcomeswithWindowsServer2008R2,a commandlikethiswillqueryeverycomputerinthedomain:


GetWmiObjectclassWin32_BIOScomputer(GetADComputerfilter*|Select expandname)

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

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