Upload
others
View
32
Download
0
Embed Size (px)
Citation preview
MasteringWindowsPowerShellScripting
TableofContents
MasteringWindowsPowerShellScripting
Credits
Foreword
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
InstantupdatesonnewPacktbooks
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Errata
Piracy
Questions
1.Variables,Arrays,andHashes
Variables
Objectsstoredinvariables
Arrays
Single-dimensionarrays
Jaggedarrays
Updatingarrayvalues
Hashes
Decidingthebestcontainerforyourscripts
Summary
2.DataParsingandManipulation
Stringmanipulation
Replacingandsplittingstrings
Countingandtrimmingstrings
TheTrimmethod
TheSubstringmethod
Thestringtrueandfalsemethods
Numbermanipulationandparsing
Formattingnumbers
Formattingbytes
Dateandtimemanipulation
Forcingdatatypes
Pipingvariables
Summary
3.ComparisonOperators
Comparisonoperatorbasics
Equalandnotequalcomparison
Greaterthanandlessthancomparison
Contains,like,andmatchoperators
And/ORcomparisonoperators
Bestpracticesforcomparisonoperators
Summary
4.Functions,Switches,andLoopsStructures
Functions
Loopingstructures
Switches
Combiningtheuseoffunctions,switches,andloops
Bestpracticesforfunctions,switches,andloops
Bestpracticesforfunctions
Bestpracticesforloopingstructuresandswitches
Summary
5.RegularExpressions
Gettingstartedwithregularexpressions
Regularexpressiongroupingconstructsandranges
Regularexpressionquantifiers
Regularexpressionanchors
Regularexpressionsexamples
Summary
6.ErrorandExceptionHandlingandTestingCode
Errorandexceptionhandling–parameters
Errorandexceptionhandling–Try/Catch
Errorandexceptionhandling–Try/Catchwithparameters
Errorandexceptionhandling–legacyexceptionhandling
Methodologiesfortestingcode
Testingthe–WhatIfargument
Testingthefrequency
Hittestingcontainers
Don’ttestinproduction
Summary
7.Session-basedRemoteManagement
UtilizingCIMsessions
Creatingasession
Creatingasessionwithsessionoptions
Usingsessionsforremotemanagement
Removingsessions
Summary
8.ManagingFiles,Folders,andRegistryItems
Registryprovider
Creatingfiles,folders,andregistryitemswithPowerShell
Addingnamedvaluestoregistrykeys
Verifyingfiles,folders,andregistryitems
Copyingandmovingfilesandfolders
Renamingfiles,folders,registrykeys,andnamedvalues
Deletingfiles,folders,registrykeys,andnamedvalues
Summary
9.File,Folder,andRegistryAttributes,ACLs,andProperties
Retrievingattributesandproperties
Viewingfileandfolderextendedattributes
Settingthemodeandextendedfileandfolderattributes
Managingfile,folder,andregistrypermissions
Copyingaccesscontrollists
AddingandremovingACLrules
Summary
10.WindowsManagementInstrumentation
WMIstructure
UsingWMIobjects
SearchingforWMIclasses
Creating,modifying,andremovingWMIpropertyinstances
Creatingpropertyinstances
Modifyingpropertyinstances
Removingpropertyinstances
InvokingWMIclassmethods
Summary
11.XMLManipulation
XMLfilestructure
ReadingXMLfiles
AddingXMLcontent
ModifyingXMLcontent
RemovingXMLcontent
Summary
12.ManagingMicrosoftSystemswithPowerShell
Managinglocalusersandgroups
Managinglocalusers
Managinglocalgroups
Queryingforlocalusersandgroups
ManagingWindowsservices
ManagingWindowsprocesses
InstallingWindowsfeaturesandroles
Summary
13.AutomationoftheEnvironment
Invokingprogramsforautomation
Usingdesiredstateconfiguration
Authoringphase
Stagingandremediationphase
Detectingandrestoringdriftingconfigurations
Summary
14.ScriptCreationBestPracticesandConclusion
Bestpracticesforscriptmanagement
#commentingheaders
Commentingcode
Bestpracticesforscriptcreation
Scriptstructure
Otherimportantbestpracticesforscriptcreation
Controllingsourcefiles
Bestpracticesforsoftwareautomation
Summary
MasteringWindowsPowerShellScripting–conclusion
Stayingconnectedwiththeauthor
Index
MasteringWindowsPowerShellScripting
MasteringWindowsPowerShellScriptingCopyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:April2015
Productionreference:1210415
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78217-355-7
www.packtpub.com
http://www.packtpub.com
CreditsAuthor
BrentonJ.W.Blawat
Reviewers
TimAmico
ChristopheCRÉMON
TomasRestrepo
AcquisitionEditor
MeetaRajani
ContentDevelopmentEditor
RohitSingh
TechnicalEditor
TanviBhatt
CopyEditors
HiralBhat
SoniaMathur
VikrantPhadke
AlphaSingh
ProjectCoordinator
MaryAlex
Proofreaders
SimranBhogal
SafisEditing
MariaGould
PaulHindle
Indexer
RekhaNair
ProductionCoordinator
AlwinRoy
CoverWork
AlwinRoy
ForewordWeallappreciatealittlesimplicitywhenitentersourbusy,complicatedlives.Technologyisnodifferent.Infact,thatiswhatweexpectfromtechnology—itshouldsimplifyourlives.Butitdoesn’talwaysworkthatway.
Sometimestechnologycanintroducevexingproblemswedon’tanticipate.
WitheveryversionofMicrosoftDOSandthenWindows,Microsoftincludedseparatecommand-lineinterfaceshells.Theshellcouldautomatesometasks,butnotallofthem.Sometaskshadtobeaccomplishedmanually,whichisantithetical—nearlyheretical—toourunderstandingoftechnology’srole.
Whatshouldhavebeensimple,automatedtasksbecameslow,frustrating,andmanualchores.Thatconundrumdidn’tgounnoticed.
Microsoftprovidedmuch-neededsimplicitywhenitintroducedPowerShellin2006.Taskautomationandconfigurationmanagementeliminatedagreatdealoftime-consumingmanualwork.Inshort,PowerShellwasagamechanger.
PowerShellhassolvedmanyofthecommand-lineandscriptingissuesthatcomplicatedourwork.Itintroducedsimplicity.Ithelpedorganizationsbecomemoreagile,moreproductive,andsavemoney.PowerShellisapowerfultool,andithasdemonstrateditspracticalvaluemanytimes.
Despiteitsutility,though,PowerShellremainsaconfusingtooltomanyITadministrators,andtheneedforgreaterclarityremains.
ItisthroughthislensthatMr.BrentonBlawatprovidesaninsightfulnewanalysisofPowerShell—avaluableguidebookforthosewhostruggletounderstandPowerShell.OthershaveofferednarrativesthatattempttoexplainPowerShell,buttheyrarelyprovidetheroadmap,background,orcontextthatadministratorsneedtogetfromPointAtoPointB.
So,thisistherighttimeforacomprehensivenewanalysis.
Ingeneralterms,Mr.Blawat’sbookwillhelpthosewhostruggletomanagetheircomputeenvironments.ItincludesimportantguidanceonprogramminginPowerShell,startingwithbasicconceptsandthenintroducingadvancedconfigurations.
Mr.Blawatdeconstructsanddemystifiesthisprogramminglanguage,sharinghisintimateknowledgeinaformatthatdemonstratestheclarityofthoughtandprosethatadifficultsubjectrequires.Manyauthorshaveattemptedthisclimb,butonlyMr.Blawathasreachedthesummit.Hisexaminationprovidesrelevantinformationforadministratorswhoworkwith—andsometimesstrugglewith—PowerShellonadailybasis.
AsMr.Blawatexplainsinthefollowingpages,therapidadoptionofcloud-basedtechnologiesparalleledthenever-endingneedforadditionalcomputingpowerindatacenters.Thiscreatedtheneedtoefficientlybuildandexpandsystemswithextremeprecision.Inadditiontoprovisioningthebasesystems,therewasaneedtodynamically
customizethesenewsystemstoworkinunisonwithcurrentrunningenvironments.
Thisdrovetheneedforthenextgenerationsystemautomationlanguagesthatwouldprovidefullconfigurationforsystemsonthefly.Notonlydotheseautomationlanguagesgreatlyreducetimetouse,buttheyalsoensurethatnomistakesaremadeduringtheconfigurationprocess.Allsystemsarecreatedequally.
PowerShellisa.NET-basednextgenerationautomationlanguagethatprovidesbothsystemsprovisioningandmanagementfunctionalityforWindows-basedsystems.Leveragingcommand-linelikeinteractions,PowerShellcanbecompiledintoscriptsthatcansystematicallyexecutetasksonasystem.Notlimitedtocreatingnewsystems,engineersareleveragingPowerShelltoautomatemundanetaskssothattheycanfocusonotherpressingactivitiesintheirenvironments.
MicrosofthasfullyembracedPowerShellinitsfullsoftwareportfoliotoofferfullintegrationwithitsproducts.NotonlycanyoudynamicallyinstalltheMicrosoftsoftware,butyoucanalsofullymanagetheentireMicrosoftsoftwareenvironmentusingPowerShell.PowerShellhasalsobeenembracedbythird-partymanufacturersthroughtheintegrationofPowerShellmodules.Thesemodulesprovidefullmanagementcapabilitiesforproductssuchasnetworkdevices,storagesubsystems,virtualizationguestsandhosts,securityappliances,andotherthird-partyapplications.
Likemanyorganizations,CDWhasbenefittedgreatlyfromPowerShell,sothisbookhitsveryclosetohomeforme.WeusePowerShellscriptstomanagecustomerenvironmentsinmanagedservicesandtheinstallationofmanagementtools.
WeuseMicrosoftOrchestratortoprovideback-endlogicforsimpleuserinterfacesforhelpdeskactivities,likeuser-drivenpasswordresetsanduser-drivensoftwareinstallations.WealsorelyonMicrosoftOrchestratortoautomaticallytroubleshootandremediatesystems.
CDW’scustomersalsobenefitfromPowerShellinmyriadways.WeassistawidevarietyofFortune500clientstodevelopPowerShellautomationscriptstobuildnewsystemsandmanagetheirenvironments,includinghealthcheckscripts,systemsdiscovery,andadvancedregulatorysecurityanalysis.
Clearly,PowerShell’sincredibleutilityhasmadeitinvaluabletoCDW,ourcustomers,andcountlessorganizationsacrosstheglobe.Butunderstandingallofitsmanyfacetsrepresentsadauntingtask.OrganizationsareunabletoleveragePowerShelliftheydon’tfullyunderstanditspotential.
That’swhereMr.Blawatexcels.
Mr.Blawat’scomprehensivenewworkwillserveasareferencetoolforengineerswhoworkwithWindowsbytakingthemysteryoutofcommontasksthataren’teasilyunderstoodandaren’talwaysintuitive.DiligentreaderswillnodoubtfindmanymorereasonstogiveMr.Blawat’sthoroughnarrativeaprominentplaceontheirbookshelves.
AsMr.Blawat’scoworker,Ialsofeelproudthatheissharinghisknowledgewiththeworld—notonlysootherscanbenefitfromhisexperience,butsotheycanseewhatthose
ofuswhoworkwithhimatCDWwitnessonadailybasis.
PowerShellhasproventobeanincrediblyusefultoolforITadministratorssinceitburstontothescene.NowthereisabookaboutPowerShellthatwillproveequallyuseful.
JonStevens
ChiefInformationOfficer
CDW
AbouttheAuthorBrentonJ.W.Blawatisanentrepreneur,strategictechnicaladvisor,author,andseniorconsultant,whohasapassionfortheprocurementoftechnologyinprofit-basedorganizations.Heisbusiness-centricandtechnology-minded.Brentonhasmanyyearsofexperienceinbridgingthegapbetweentechnicalstaffanddecision-makersinseveralorganizations.Hetakesprideinhisabilitytoeffectivelycommunicatewithadiverseaudienceandprovidestrategicdirectionforlargeandsmallorganizationsalike.
In2013,Brentonauthoredhisfirstbook,PowerShell3.0WMIStarter,PacktPublishing.ThisbookwasdesignedtobeastarterforthoseinterestedinmanipulatingWindowsManagementInstrumentationthroughtheuseofPowerShell3.0.Thisbookisavailableinallpopularbookstores,includingPacktPublishing’swebsite,http://bit.ly/18pcpGK.
BrentoncurrentlyworksatCDWasaseniorconsultingengineerinstrategicsolutionsandservices.CDWisaleadingmultibrandtechnologysolutionsproviderinthefieldsofbusiness,government,education,andhealthcare.AFortune500company,itwasfoundedin1984andemploysapproximately7,200coworkers.In2014,thecompanygeneratednetsalesofmorethan$12.0billion.FormoreinformationaboutCDW,youcanvisitwww.CDW.com.
Iwouldliketothanktheforewordcoordinationteam,MaryViola,ScottThomas,JimmyThomson,BrandonKing,SondraRagusin,MeredithBraselman,andBillGlanz.Iwouldliketodedicatethisbooktomybeautifulnieces,CaliettandEvie.
http://bit.ly/18pcpGKhttp://www.CDW.com
AbouttheReviewersTimAmicoisaconsultingengineeratCDW,whospecializesinConfigurationManagerandOperatingSystemDeployment.HestartedhiscareerinITbackin1998,whenheworkedasaconfigurationtechforCompuCom,learningaboutwhatisrequiredtobecomeanITprofessional.Sincethen,hehasclimbedtheladderfromhardwarefieldsupportandsoftwaredeploymentsupporttohiscurrentrole(forthelast10years)asanITconsultant,designingandimplementingendpointandmobilitymanagementsolutions.ApartfromConfigurationManagerandOSD,TimalsohasexperienceinPowerShell,BitLockerdriveencryptiondeployments,IntelvProprovisioningandusecasedesign,ActiveDirectory(bothinAzureandWindowsServer),SQLdesignandreporting,PKIdesign,andMicrosoftIntune.
ChristopheCRÉMONisaSharePointinfrastructurearchitect,with10yearsofexperienceininformationtechnology,especiallyMicrosoft.HehasbeenusingPowerShellsince2008,andhaspublishedusefulscriptsandmodulesforITAdministratorsatpowershell.codeplex.com.Hehasapersonalwebsiteatwww.christophecremon.com.
TomasRestrepohasbeenwritingsoftwareforover10years,startingwithC/C++andeventuallymovingtothe.NETplatform.Hecurrentlyspendsmostofhistimehelpingotherdeveloperssolvecomplexproblemsandtroubleshootingapplicationperformanceandscalabilityissues.
http://powershell.codeplex.comhttp://www.christophecremon.com
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmoreForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusatformoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.
http://www.PacktPub.comhttp://www.PacktPub.commailto:[email protected]://www.PacktPub.comhttps://www2.packtpub.com/books/subscription/packtlib
Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
http://www.PacktPub.com
InstantupdatesonnewPacktbooksGetnotified!Findoutwhennewbooksarepublishedbyfollowing@PacktEnterpriseonTwitterorthePacktEnterpriseFacebookpage.
PrefacePowerShellisanetworkscriptinglanguagethatprovidesasetoftoolstoadministerMicrosoftproducts.WhilePowerShellisbasedoncommand-lineinteractions,itismuchmorepowerfulthanwhatthestandardcommandlineoffers.Ithasbuilt-insectionsofcodecalledcmdlets.Theysimplifyfunctionsthatyoumayneedtoperformonasystem.Usingcmdletsgreatlyreducesthenumberoflinesofcodethatarerequiredtoperformactions,comparedtootherscriptinglanguages,suchasVBScript.
PowerShellisbasedontheverb-nounnamingconvention,whichallowsscripterstodeclareanactionfollowedbyanobjecttoconfigure.Forexample,theget-servicecmdleteasilydesignatesthatyouaregettingaWindowsservice.ThisliteralnamingconventionhelpsreadersquicklylearnhowtoprograminPowerShell,astheactionsareeasilyremembered.
CommunitysupportforPowerShellhasgrownastronomically.NotonlyhavelargecompaniesadoptedPowerShellintheirenvironments,butuniversitiesarealsoregularlyteachingPowerShellcoursestotheirstudents.PowerShell’sfeaturesetkeepsgrowingwitheveryreleaseoftheproduct.Itisconceivableinthenearfuturethatyouwillbeabletofullyautomatetheconfigurationofeverycomponentinadatacenter.Thiswillremovetheneedsofmultipleengineeringspecialiststoprovisionnetworking,storage,firewalls,operatingsystemsbuilds,andhigh-availabilityconfigurations.ItwillallbedoneviaPowerShellscriptingandthesystemswillbeabletobeconfiguredusingasingularnetworklanguage.
ThisbookprovidesastrongfoundationforlearningPowerShellusingreal-worldscenarios.Youwillnotonlybeabletoquicklylearnhowtoprograminthislanguage,butalsobeabletoproducescriptsthatyoucanuseinyourexistingenvironments.Thisbookwillalsobeagreatreferencebookforyoutolookbackonandrevisitasyouarecoding.Itwillprovidethepropersyntaxandshowyousuccessfulwaystoimplementyourcode.Whenyouaredonewithreadingthisbook,youwillbewellonyourwayto“masteringPowerShell”!
WhatthisbookcoversChapter1,Variables,Arrays,andHashes,exploresthedifferentdataandobjectcontainersthatyoucanuseinPowerShell.Thesecontainersincludevariables,arrays,andhashes.Thischapterprovidesexamplesonhowtousethesecontainerstostoreobjects.
Chapter2,DataParsingandManipulation,divesintothedifferentdatatypesandhowtomanipulatetheminyourscripts.Thesedatatypeexamplesincludestrings,integers,dates,XML,andmanymore.
Chapter3,ComparisonOperators,evaluatesmultiplecomparisonoperatorsanddisplayshowtouseeachofthesecomparisonoperators.Thischapteralsodisplayshowtoleverageimpliedtrueandfalsecomparisonoperators.
Chapter4,Functions,Switches,andLoopsStructures,displaystheuseofdifferentdatastructurestoperformrepeatableactions.Itprovidesexamplesonhowtoparselargearraysofdatathroughloopingstructuresandhowtoincludeoverloadparametersinthesestructures.
Chapter5,RegularExpressions,exploresPowerShell’simplementationofregularexpressions.Itevaluatesthebuilt-incomparisonoperatorsthatprovideexpressionvalidationandhowtocreatecomplexexpressions.
Chapter6,ErrorandExceptionHandlingandTestingCode,showsyouhowtocreatecodeinarobustmannertoavoidexceptionsduringexecution.Thischapterexplainsvariousbuilt-inerrorandexceptionhandlingtechniques,aswellassupportforlegacysystemsthatdon’tsupportPowerShellcmdlettriggers.Italsoexplainsthedifferentitemstobeawareofduringthetestingcycleofyourcode.
Chapter7,Session-basedRemoteManagement,providesaninsightintosession-basedmanagementthroughPowerShell.Itdisplayshowtoleveragethebuilt-inWinRMtoexecuteitemsonremotesystems.
Chapter8,ManagingFiles,Folders,andRegistryItems,displayshowtoquery,create,modify,anddeleteitemsinthefilesystemandregistry.Thisincludesfiles,folders,registrykeys,registry-namedvalues,andproperties.
Chapter9,File,Folder,andRegistryAttributes,ACLs,andProperties,divesdeepintotheinterworkingoffiles,folders,andregistries.Thischapterexplainshowtosetfileandfolderstandardsandadvancedattributes.ItalsodisplayshowtomanipulateACLstosetpermissionsonfiles,folders,andregistryitems.
Chapter10,WindowsManagementInstrumentation,explainshowtouseWindowsManagementInstrumentation(WMI)toquerylocalandremotesystemsforadvancedsysteminformationandthedifferentcmdletsthatprovideaccesstoasystem’sWMI.
Chapter11,XMLManipulation,exploreseXtensibleMarkupLanguage(XML)andshowsyouhowtointeractwithitusingPowerShell.ThischapterexplainsthedifferentcomponentsthatmakeupaproperXMLdocumentandhowtointeractwiththeseindividualcomponents.
Chapter12,ManagingMicrosoftSystemswithPowershell,providesinformationonhowtoworkwithWindowsusersandgroups,Windowsservices,Windowsprocesses,andthemanipulationofWindowsfeaturesandroles.
Chapter13,AutomationoftheEnvironment,explainshowtoinvokeitemsforusewithautomationscripts.Thischapterexplainsparentandchildrelationshipsbecausetheypertaintolinkingscriptstogether.ItalsoexploresDesiredConfigurationManagement(DCM)andconfigurationbaselines.
Chapter14,ScriptCreationBestPracticesandConclusion,providesbestpracticerecommendationsforutilizingPowerShellinyourenvironment.Thischapterconcludeswithsomefinalthoughtsfromtheauthor.
WhatyouneedforthisbookToworkthroughtheexamplesprovidedinMasteringWindowsPowerShellScripting,youwillneedaccesstoWindows7orahigherWindowsoperatingsystem.YouwillalsoneedServer2008R2orahigherWindowsServeroperatingsystem.ThechaptersinthisbookrelyhighlyonWindowsManagementFramework4.0(PowerShell4.0)andRemoteServerAdministrationTools.Youwillneedtodownloadandinstallbothofthesesoftwarepackagesonthesystemsyouarerunningtheseexampleson.
WhothisbookisforMasteringWindowsPowerShellScriptinghasbeendesignedforPowerShellscripterswhocanbebothbeginnersandadvanced-levelcoders.Byreadingthisbook,youwillbeabletogainin-depthknowledgeofPowerShellandthebestpracticestodevelopscriptsusingthisautomationlanguage.Previousscriptingandcodingexperiencewillbehelpful,thoughitisnotrequired.
ConventionsInthisbook,youwillfindanumberofstylesoftextthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestyles,andanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Theget-servicecmdletisusedtoretrievedetailedinformationaboutWindowsservices.”
Anycommand-lineinputoroutputiswrittenasfollows:
#Retrievetheservicesstatusandstarttheserviceifitisstopped.$status=(Get-service–DisplayName"WindowsAudio").StatusIf($status–like"Stopped"){start-service–DisplayName"WindowsAudio"}
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,inmenusordialogboxesforexample,appearinthetextlikethis:“Toaddafirewallruleonasystemusingthenetshcommand,youneedtoopenPowerShellwiththeRunasAdministratoroption”
NoteWarningsorimportantnotesappearinaboxlikethis.
TipTipsandtricksappearlikethis.
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.
Tosendusgeneralfeedback,simplysendane-mailto,andmentionthebooktitleviathesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.
mailto:[email protected]://www.packtpub.com/authors
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
http://www.packtpub.comhttp://www.packtpub.com/support
ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyouwouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheerratasubmissionformlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedonourwebsite,oraddedtoanylistofexistingerrata,undertheErratasectionofthattitle.Anyexistingerratacanbeviewedbyselectingyourtitlefromhttp://www.packtpub.com/support.
http://www.packtpub.com/submit-erratahttp://www.packtpub.com/support
PiracyPiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusatwithalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.
mailto:[email protected]
QuestionsYoucancontactusatifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.
mailto:[email protected]
Chapter1.Variables,Arrays,andHashesPowerShellprovidesavarietyofmechanismstostore,retrieve,andmanipulatedatausedinyourscripts.Thesestorage“containers”arereferredtoasvariables,arrays,andhashes.Theycanbeusedascontainerstostorestrings,integers,orobjects.Thesecontainersaredynamicastheyautomaticallydetectwhattypeofdataisbeingplacedwithinthem.Unlikeotherobject-orientedlanguages,thereisnoneedtodeclarethecontainerpriortouse.Todeclareoneofthesecontainers,youusethedollarsign($)andthecontainername.
Anexampleofacontainerwouldlooklikethis:
$myVariable
Duringthischapter,youwilllearnthefollowingconcepts:
VariablesArraysHashesDecidingthebestcontainerforyourscripts
Whenyouarecreatingnamesforcontainers,itisindustrybestpracticetousenamesthatarerepresentativeofthedatatheyarestoring.WhilecontainersarenotcasesensitiveinPowerShell,itisacommonpracticetousecamelCasewhenwritingcontainernames.camelCaseisachievedbykeepingthefirstletterofthecontainerlowercaseandthesubsequentfirstlettersofeachwordcapitalized.SomevariationsofcamelCasepermitthefirstlettertobecapitalized.Thisformattingaidsineasyreadingofthecontainers.
AnexampleofacontainerusingcamelCasewouldlooklikethis:
$webServerIPAddress
VariablesVariablesareoneofthemostwidelyusedcontainersinPowerShellduetotheirflexibility.Avariableisacontainerthatisusedtostoreasinglevalueoranobject.Variablescancontainavarietyofdatatypesincludingtext(string),numbers(integers),oranobject.
Ifyouwanttostoreastring,dothefollowing:
$myString="MyStringHasMultipleWords"$myString
Theoutputofthisisshowninthefollowingscreenshot:
TheprecedingvariablewillnowcontainthewordsMyStringHasMultipleWords.Whenyououtputthe$myStringvariable,asshownintheprecedingscreenshot,youwillseethatthestringdoesn’tcontainthequotations.ThisisbecausethequotationstellthePowerShellcommand-lineinterpretertostorethevaluethatisbetweenthetwopositionsorquotations.
TipYouareabletoreusevariableswithoutdeletingthecontentalreadyinsidethevariable.ThePowerShellinterpreterwillautomaticallyoverwritethedataforyou.
Subsequently,ifyouwanttostoreanumber,dothefollowing:
$myNumber=1$myNumber
Theoutputofthisisshowninthefollowingscreenshot:
Thismethoddifferentiateswhilestoringastringasyoudonotusequotations.ThiswilltellthePowerShellinterpretertoalwaysinterpretthevalueasanumber.Itisimportanttonotusequotationswhileusinganumber,asyoucanhaveerrorsinyourscriptifthePowerShellinterpretermistakesanumberforastring.
Anexampleofwhathappenswhenyouusestringsinsteadofintegerscanbeseenhere:
$a="1"$b="2"$c=$a+$b$c
Theoutputofthisisshowninthefollowingscreenshot:
The$cvariablewillcontainthevalueof12.ThisisduetoPowerShellinterpretingyour$astringof1and$bstringof2andputtingthecharacterstogethertomake12.
Thecorrectmethodtodothemathwouldlooklikethis:
$a=1$b=2$c=$a+$b$c
Theoutputofthisisshowninthefollowingscreenshot:
Sincethe$aand$bvariablesarestoredasnumbers,PowerShellwillperformthemathonthenumbersappropriately.The$cvariablewillcontainthecorrectvalueof3.
ObjectsstoredinvariablesObjectsarevastlydifferentthanstringsandnumbers.ObjectsinPowerShellaredatastructuresthatcontaindifferentattributessuchaspropertiesandmethodswithwhichonecaninteract.Objectpropertiesaredescriptorsthattypicallycontaindataaboutthatobjectorotherrelatedobjects.Objectmethodsaretypicallysectionsofcodethatallowyoutointeractwiththatobjectorotherobjectsonasystem.Theseobjectscaneasilybeplacedinvariables.Youcansimplyplaceanobjectinavariablebydeclaringavariableandplacinganobjectinit.Toviewalloftheobject’sattributes,youcansimplycallthevariablecontainingtheobject,useapipecharacter|,andusetheget-membercmdlet.
Toplaceanobjectinavariableandretrieveitsattributes,youneedtodothis:
$date=get-date$date$date|get-member
Theoutputisshowninthefollowingscreenshot:
Inthisexample,youwilllearnhowtoplaceanobjectintoavariable.Youfirststartbydeclaringthe$datevariableandsettingitequaltotheoutputfromtheget-datecmdlet.Whenyouexecutethis,theget-datecmdletreferencestheSystem.Dateclass,andthe$datevariableinheritsallofthatobject’sattributes.Youthencallthe$datevariableandyouseethattheoutputisthedateandtimefromwhenthatcommandwasrun.Inthisinstance,itisdisplayingtheDateTimeScriptPropertyattributeonthescreen.ToviewalloftheattributesoftheSystem.Dateobjectinthe$datevariable,youpipethoseresultstotheget-membercmdlet.Youwillseealloftheattributesofthatobjectdisplayedonthescreen.
Ifyouwanttousethepropertiesandmethodattributesofthatobject,youcansimplycallthemusingdotnotation.Thisisdonebycallingthevariable,followedbyaperiod,and
referencingthepropertyormethod.
Toreferenceanobject’spropertiesandmethodattributes,youneedtodothis:
$date=get-date$date.Year$date.addyears("5")
Theoutputofthisisshowninthefollowingscreenshot:
Thisexampleshowsyouhowtoreferenceanobject’spropertiesandmethodattributesusingdotnotation.Youfirststartbydeclaringthe$datevariableandsettingitequaltotheoutputfromtheget-datecmdlet.Whenyouexecutethis,theget-datecmdletreferencestheSystem.Dateclass,andthe$datevariableinheritsallofthatobject’sattributes.YouthenleveragedotnotationtoreferencetheYearpropertyattributebycalling$date.Year.Theattributewillreturn2015astheYearproperty.YouthenleveragedotnotationtousetheAddYears()methodtoincreasetheyearsby5.Afterenteringthe$date.addyears("5")command,youwillseeanoutputonthescreenofthesamemonth,day,andtime;however,theyearisincrementedby5years.
ArraysArraysarethesecondmostusedcontainersinPowerShell.Anarray,insimpleterms,isamulti-dimensionalvariableoravariablecontainingmorethanonevalue.Thetwocorecomponentstoanarrayaretheindexnumberandthepositionvalue.Whenyouuseanarray,youreferenceanindexnumberanditwillreturnthepositionvalue.
Single-dimensionarraysThefollowingtablerepresentsanarraywithasingledimension:
Indexnumber Positionvalue
0 Example1
1 Example2
2 Example3
3 Example4
4 Example5
Whenyouarestoring,manipulating,orreadingthedatainanarray,youhavetoreferencethepositioninthearraythedataisresiding.Thenumberspopulatedinthetable’sIndexnumbercolumnarerepresentativeofthelocationwithinthearray.Youwillseethatarray’snumberingstartsatthenumber0,andsothefirstdatawouldbeincell0.Ifyoucallthearrayatposition0,theresultwouldbethepositionvalueofExample1.Whenbuildingthearray,youwillseethateachvalueinthearrayvaluesisseparatedbyacomma.ThistellsthePowerShellinterpretertosetanewarrayvalue.
First,youcanstartbybuildingthearrayintheprecedingtablebyenteringthefollowingcommand:
$myArray="Example1","Example2","Example3","Example4","Example5"$myArray
Theoutputofthisisshowninthefollowingscreenshot:
Theprecedingexampledisplayshowtocreateanarrayofstrings.Youfirststartbydeclaringavariablenamed$myArray.Youthenplacemultiplestringsoftextseparatedbycommastobuildthearray.Afterdeclaringthearray,youcallthe$myArrayarraytoprintthevaluestotheconsole.ItwillreturnExample1,Example2,Example3,Example4,andExample5.
Retrievingdataataspecificpositioninanarrayisdonethroughtheuseofbrackets.Toretrievethevalueof0fromthearray,youwoulddothefollowing:
$myArray="Example1","Example2","Example3","Example4","Example5"$myArray[0]
Theoutputofthisisshowninthefollowingscreenshot:
Theprecedingexampledisplayshowyoucanobtainarraydataataspecificposition.Youfirststartbydeclaringavariablenamed$myArray.Youthenplacemultiplestringsoftextseparatedbycommastobuildthearray.Afterdeclaringthearray,youcall$myArray[0]toaccessthepositionvalueofindexnumber0fromthearray.TheprecedingexamplereturnsthevalueofExample1fortheindexnumber0.
JaggedarraysArrayscanbecomemorecomplexasyoustartaddingdimensions.Thefollowingtablerepresentsajaggedarrayoranarrayofarrays:
Indexnumber Positionvalue0 Positionvalue1
0 Example1 Red
1 Example2 Orange
2 Example3 Yellow
3 Example4 Green
4 Example5 Blue
Whileaccessingdatainajaggedarray,youwillneedtoreadthecellvaluescountingat0forbothdimensions.Whenyouareaccessingthedata,youstartreadingfromtheindexnumberfirstandthenthepositionvalue.Forexample,theExample1dataisintheindexnumberof0andthepositionvalueof0.Thiswouldbereferencedasposition[0][0].Subsequently,thedataBlueisintheindexnumberof4andpositionvalueof1.Thiswouldbereferencedasposition[4][1].
Todothisforyourself,youcanbuildtheprecedingtablebyenteringthefollowingcommand:
$myArray=("Example1","Red"),("Example2","Orange"),("Example3","Yellow"),("Example4","Green"),("Example5","Blue")$myArray[0][0]$myArray[4][1]
Theoutputisshowninthefollowingscreenshot:
Thisexampledisplayshowtocreateajaggedarrayandaccessingvaluesinthearray.Youfirststartbuildingthejaggedarraybydeclaringthefirstarrayof"Example1""Red",secondarrayof"Example2""Orange",thirdarrayof"Example3""Yellow",fourtharrayof"Example4""Green",andfiftharrayof"Example5""Blue".Afterbuildingthearray,youaccessthewordExample1byreferencing$myArray[0][0].YouthenaccessthewordBluebyreferencing$myArray[4][1].
UpdatingarrayvaluesAfteryoucreateanarray,youmayneedtoupdatethevaluesinsidethearrayitself.Theprocessforupdatingvaluesinanarrayissimilartoretrievingdatafromthearray.Firstyouneedtofindthecelllocationthatyouwanttoupdate,andthenyouneedtosetthatarraylocationasequaltothenewvalue:
Indexnumber Positionvalue0 Positionvalue1
0 John Doe
1 Jane Smith
Giventheprecedingtable,ifJane’slastnameneededtobeupdatedtodisplayDoeinsteadofSmith,youwouldfirstneedtolocatethatdatarecord.Thatincorrectlastnameislocatedatindexnumber1andpositionvalue1,or[1][1].Youwillthenneedtosetthatdatalocationequal(=)toDoe.
Todothis,youneedtoenterthefollowingcommand:
$myArray=("John","Doe"),("Jane","Smith")$myArray$myArray[1][1]="Doe"$myArray
Theoutputofthisisshowninthefollowingscreenshot:
Thisexampledisplayshowyoucancreateanarrayandupdateavalueinthearray.Youfirststartbydefining$myArrayanduse"John","Doe","Jane",and"Smith"asthearrayvalues.Aftercallingthevariabletoprintthearraytothescreen,youupdatethevalueinindexnumber1,positionvalue1,or$myArray[1][1].BysettingthispositionequaltoDoe,youchangethevaluefromSmithtoDoe:
Indexnumber Positionvalue0 Positionvalue1
0 John Doe
1 Jane Smith
2 Sam Smith
Ininstanceswhereyouwanttoappendadditionalvaluestothearray,youcancallthearrayvariablewiththe+=commandandthedatayouwanttoaddtothearray.Thislookslike$array+="NewArrayValues".The+=commandisamoreefficientmethodofperformingthecommands$array=$array+"NewArrayValues".
Toadddataintoanarrayandmaketheprecedingtable,youcandothefollowingoperation:
#CreatetheArray$myArray=("John","Doe"),("Jane","Smith")$myArray#AppendDatatotheArray$myArray+=("Sam","Smith")$myArray
Theoutputofthisisshowninthefollowingscreenshot:
Inthisexample,youaddvaluestoanexistingarray.Youfirststartbydefininganarrayof$myArray.Youthenprinttheexistingcontentsofthearraytothescreen.Youthenaddadditionalcontentbysettingthearray+=tothenewarraydataof("Sam","Smith").Afterreprintingthecontentsofthearraytothescreen,youseethevaluesSamandSmithaddedtothearray.
TipTosearchandremoveitemsfromanarray,youwillneedtocreateaForEachlooptocyclethroughalloftheindexnumbersandpositionvalues.Chapter4,Functions,Switches,andLoopStructures,explorestheForEachloopingstructure.
HashesHashesareusedlikearrays.Themaindifferenceisthattheyusethevaluesasindexesversussequentiallynumberedindexes.Thisprovideseasyfunctionalitytoadd,remove,modify,andfinddatacontainedinthehashtable.Hashtablesareusefulforstaticinformationthatneedsadirectcorrelationtootherdata:
Name Value
John.Doe Jdoe
Jane.Doe jdoe1
AgoodexampleofahashtablewouldbeintheinstanceofanActiveDirectorymigration.InmostActiveDirectorymigrations,youwouldneedtocorrelateoldusernamestonewusernames.Theprecedingtablerepresentsausernamemappingtableforthesetypesofmigrations.Whileatraditionalarraywouldwork,ahashtablemakesthismucheasiertodo.
Tocreatetheprecedinghashtable,enterthefollowingcommand:
$users=@{"john.doe"="jdoe";"jane.doe"="jdoe1"}$users
Theoutputofthisisshowninthefollowingscreenshot:
Afteryoucreatethetable,youmaywanttofindaspecificuser.Youcansearchahashtablebyusingthehash’sindexingfunction.Thisisdonebycalling$hashName["value"].Anexampleofthiswouldlooklikethefollowingcommand:
$users=@{"john.doe"="jdoe";"jane.doe"="jdoe1"}$users["john.doe"]
Theoutputofthisisshowninthefollowingscreenshot:
Afterenteringthecommand,youwillseethat$users["john.doe"]returnsjdoeasthecorrelatingvalueinthehash.
Oneofthemostpopularmethodstousewithhashtablesistheaddmethod.Theadd
methodallowsyoutoenternewvalueswithinthehashtable.Youcanusethiswhilebuildingthehashtable,asmosthashtablesarebuiltwithinascript.Ifyouwanttoaddanotherusertothehashtable,usetheaddmethodasshownhere:
$users=@{"john.doe"="jdoe";"jane.doe"="jdoe1"}$users$users.add("John.Smith","jsmith")$users
Theoutputofthisisshowninthefollowingscreenshot:
YouwillseethatJohn.Smithwiththevalueofjsmithisnowaddedtothehashtable.
Youcanalsoupdatevaluesinahashbyleveragingthehash’sindex.Thisisdonebysearchingforavalueandthensettingitscorrelatinghashvalueequaltoanewvalue.Thislookslike$arrayName["HashIndex"]="Newvalue".Anexampleofthisisgivenhere:
$users=@{"john.doe"="jdoe";"jane.doe"="jdoe1"}$users$users["jane.doe"]="jadoe"$users
Theoutputofthisisshowninthefollowingscreenshot:
YouwillseethatthemappedvalueforJane.Doenowreadsjadoe.Thisisvastlydifferent
fromanarray,whereyouwouldhavetosearchforaspecificvaluelocationtoreplacethevalue.
Ifyouwanttoremoveauserfromthehashtable,usetheremovemethod,asshownhere:
$users=@{"john.doe"="jdoe";"jane.doe"="jdoe1"}$users$users.remove("Jane.Doe")$users
Theoutputofthisisshowninthefollowingscreenshot:
YouwillseethatJane.Doeisnowremovedfromthehashtable.Thismethodishelpfulwhenyouneedtoremovespecificvalues,whichmeetcertaincriteria,fromthehashtable.
DecidingthebestcontainerforyourscriptsWhenyouarescripting,itisimportanttoputconsiderationintowhatkindofcontaineryouwillbeusing.Sometimesthesimplicityofcreatingasingularvariableandupdatingthatvariableislesscomplexthancreatinganarrayorhashtabletosearchthrough.Atothertimes,itmaybemoreefficienttopullthewholedatasetanduseindividualpiecesofthatdatawithinyourscript.
Single-linevariablescanbeusedfor:
MathoperationsthatrequirecalculationsofsingleormultiplevaluesCatchingsingle-lineoutputfromexecutinganon-PowerShellcommandTrackingcurrentpositioninalooplike“percentcomplete”
Arraysarebestusedfor:
StoringalistofitemsforindividualprocessingwithinascriptDumpingerrorinformationfromaPowerShellcmdlet
Hashesarebestusedfor:
MappingdatafromonevaluetoanothervalueDatathatrequiresfrequentsearching,updating,orbuildingduringscriptexecutionStoringmultiplevaluesofcorrelateddatalikeuserobjectattributes
SummaryThischapterexplorestheuseofavarietyofcontainers.Youlearnedthatvariables,arrays,andhasheshavethecommonalityofbeingabletostoredata,buttheydoitindifferentways.Youlearnedthatdifferenttypesofdatacanbestoredinthesecontainers.Thesetypesofdataincludenumbers,strings,andobjects.
Thischapterexploredthatvariablesarebestusedforthestorageofsingle-dimensionaldatasets.ThesedatasetscancontainstringsbutalsoincludemathematicalequationsthatPowerShellhastheabilitytoinherentlycalculate.Youalsonowknowthatarraysareprimarilyusedinsituationswhereyouwanttostoremorethanonesetofdata.Youareabletonavigate,add,andremovevaluesinthearraybasedoffofastartingvalueof0.Last,youlearnedthathashesarebestusedwhilecorrelatingdatafromonevaluetoanother.Youareabletoadd,remove,andsearchdatacontainedinthehashtableswiththeuseofsimplecommands.Inthenextchapter,youwilllearntechniquestoperformdataparsingandmanipulationbyleveragingvariablesandarrays.
Chapter2.DataParsingandManipulationOneofthemostpowerfulfeaturesofPowerShellisitsabilitytoretrieveandmanipulatedata.ManyatimeswhenyouretrievedatafromaPowerShellsession,theformatinwhichitisavailableisdifferentfromwhatyouwouldwanttodisplayinthePowerShellwindoworinalogfile.Forthispurpose,PowerShellprovidespowerfulcmdletsandmethodstoperformdatamanipulationtobestsuityourneedsasaPowerShellscripter.
Whilereadingthischapter,you’lllearnthefollowingconcepts:
StringmanipulationNumbermanipulationandparsingDate/timemanipulationForcingdatatypesPowerShellpipeline
StringmanipulationStringmanipulationissomethingthatyou’llneedtodoinalmosteveryscriptyoucreate.Whilesomeofthestringmethodswillbeusedmoreoftenthanothers,theyallservedifferentpurposesforyourscript.Itisultimatelyuptoyourcreativityonhowyouwantdatatolookwhenitisdisplayedonthescreen.
Tochangethetexttouppercase,executethefollowingcommand:
$a="Error:Thisisanexampleerror"$a.toUpper()
Theoutputofthisisshowninthefollowingscreenshot:
ThetoUpper()methodisusedtoformatthetexttouppercase.Thisishelpfulinsituationswheremessagesneedtobeemphasizedorshouldstandout.Theresultofthiscommandwillchangethecase.
Tochangethestringtolowercase,executethefollowingcommand:
$string="TheMACAddressis"$mac="00:A0:AA:BB:CC:DD"$message=$string+$mac.toLower()$message
Theoutputofthisisshowninthefollowingscreenshot:
TheinverseoftoUpper()istheuseoftoLower().Thiscommandwillconverttheentirestringtolowercaseintheinstancewhenyoudonotwanttoemphasizeastring.toLower()istypicallyusedinsituationswhereasinglewordoravariableisuppercase,andyouwanttotransitionittolowercase.Thiscommandshowstakingtwoseparatestrings,formattingthe$MACstringtothelowercase,andoutputtingbothvariablestogether.
ReplacingandsplittingstringsPowerShellalsoprovidestheabilitytoreplacecharactersinstringsusingtheReplace()method.Thisisusefulwithinyourscriptswhenyouhavetoreplacecharactersfromtheoutputofanothermethod.Forinstance,ifyoupullalistofcommonusernamesfromActiveDirectory,theyareprefixedwithcn=.IfyouwantedtoreplaceCN=withnothing(""),youcaneasilyaccomplishthiswiththeReplace()method.
Toreplaceitemsinastring,executethefollowingcommand:
$usernames="CN=juser,CN=jdoe,CN=jsmith,CN=bwhite,CN=sjones"$usernames=$usernames.replace("CN=","")$usernames
Theoutputofthisisshowninthefollowingscreenshot:
ThisscriptwillreplacethecharactersCN=withnothingasdesignatedby"".Theoutputofthisscriptisalistofusernameswithcommaseparators.Asyoucansee,thisisveryhelpfulinthemanipulationofthedatabeingoutputfromActiveDirectory.Buildingonthepriorexample,ifyouwantedtoprocesstheusernamesindividually,youcanleveragethesplit()method.Thesplit()methodwillseparatevaluesinastring,bydeclaringaspecificcharactertosplit.
Tosplititemsinastring,executethefollowingcommand:
$usernames="juser,jdoe,jsmith,bwhite,sjones"$userarray=$usernames.split(",")$userarray
Theoutputofthisisshowninthefollowingscreenshot:
Whenyouleveragethesplit()method,asshowninthisexample,thescriptusesthecommaasdesignationthatthenextitemneedstobeanewvaluewithinthearray.Theoutputfromthisscriptallowsyoutointeractwiththeseusernamesindividually.Youwillfrequentlyusethesplit()methodwhileworkingwithcommaseparatedvalues(CSV)filesorXMLfiles.It’scommonforthesetypesoffilestocontainmultipleobjectsperline,whichmakessensetoleveragethesplit()method.
CountingandtrimmingstringsPowerShellhastwomethodstocountobjectswithinvariablesandarrays.ThefirstisdonebyusingtheCountmethod.TheCountmethodisusedtocountthenumberofobjectsthatarecontainedwithinanarray.Thisisusefulwhenyouareattemptingtodeterminethequantityofitemsyou’llbeprocessingwithinyourscript.
Tocountitemsinanarray,executethefollowingcommand:
$services=get-service$services.count
Theoutputofthisisshowninthefollowingscreenshot:
Agoodexampleofdetermininghowmanyobjectsarepresentinanarrayisobtainingthenumberofservicesrunningonasystem.ThepreviouscommanddisplaysaqueryoftheservicesonaboxandusestheCountmethodtoobtainthequantityofservices.Thesysteminthisexamplehas210services.
Thesecondmethodtocountobjectsisusedforinstancesinyourscriptswhereyouneedtodeterminethelengthorthenumberofcharactersinastring.ThisiscompletedbyusingtheLengthmethod.TheLengthmethodwillcountthenumberofcharactersinastring,includingspaces,andoutputthequantityofcharacters.
AcommonscenariowhereyouwouldusetheLengthmethodiswithWindowsfileandfolderpaths.SincetheWindowsoperatingsystemsarewellknownforhavingafilepathlimitationof255characters,wecanleveragetheLengthmethodtoqualifyincaseswherethepathisoverthatlimitation.
Togetthelengthofastring,executethefollowingcommand:
$path="c:\windows\system32\drivers\1394bus.sys"$path.length
Theoutputofthisisshowninthefollowingscreenshot:
Inthisexample,youarecountingthenumberofcharactersinafileandfolderpathtoensurethatyoudonotexceedthemaximumnumberofcharacters.Thiscommandcountedthelengthof$pathtobe39characters.Throughthiscommand,you’vedeterminedthatitisnotoverthelimitationsoftheWindowsoperatingsystem.
TheTrimmethodAsyouscript,you’llrunintosituationswheretheoutputfromacommandortheinputfromafilemaynotbeinaformatthatcanbeeasilyparsed.Forexample,ifyouimportvaluesfromaCSVfileandthosevalueshaveextraspaces,itcancauseyourscripttofail.PowerShellprovidestheabilitytotrimstringsofspacesandothercharacterswiththeTrim()method.TheTrim()methodcomesinthreedifferentvariations,whichareTrim(),TrimStart(),andTrimEnd().
Totrimthespacesoutofastring,usethefollowingcommand:
$csvValue="servername.mydomain.com"$csvValue.trim()
Theoutputofthisisshowninthefollowingscreenshot:
Bydefault,whenyouusetheTrim()methodwithoutdeclaringanycharacterstotrim,itwillautomaticallyremovethespacesthatsurroundthetextvaluesinastring.Thisexampledisplaysacomputernamethatissurroundedbyspaces.AfterrunningtheTrim()method,you’llseethatthespacesaresuccessfullytrimmedfromthestring.
Totrimvaluesoutofastring,executethefollowingcommand:
$csvValue="servername.mydomain.com"$csvValue=$csvValue.trim(".mydomain.com")$csvValue
Theoutputofthisisshowninthefollowingscreenshot:
Ifyouwanttotrimaspecificvaluefromastring,youcandeclareitwithintheTrim()method.Byexecutingtheprecedingscript,you’llseethatdeclaringatextvalueof.mydomain.comwithintheTrim()methodwillremovethosecharactersfromtheentirestring.
TheTrimStart()methodprovidesthesamefunctionalityoftheTrim()method;however,itonlyremovescharactersfromthebeginningofthestring.Likewise,theTrimEnd()methodwillonlyremovecharactersfromtheendingofthestring.Thesearehelpfulinsituationswhereyouneedtoparsethedataintovaluesthatcanbereadeasily.
Totrimthebeginningandendofastring,executethefollowingcommand:
$csvValue="FQDN:servername.mydomain.com"
$csvValue=$csvValue.trimStart("FQDN:")$csvValue=$csvValue.trimEnd(".mydomain.com")$csvValue
Theoutputofthisisshowninthefollowingscreenshot:
TheprecedingexampledisplaystheuseofbothTrimStart()andTrimEnd()methods.Inthisexample,youtrimthe"FQDN:"charactersfromthestartofthestringand.mydomain.comfromtheendofthestring.Thefinaloutputofthisisservername.
WhenyouusetheTrim()method,you’llwanttorememberthatitwillremoveallinstancesofthewordsfoundatthebeginningandendingofthestring.Ifyouusedcomputernameinsteadofservername,youwouldhavenoticedthattheoutputfromthemethodwouldhaveputername.TheTrim()methodwouldhavematchedthewordscomandremoveditfromthestring.ItisbesttousetheTrim()methodtoremovespacesandunneededcharactersinstrings.UsetheReplace()methodtoremoveseriesofstringssuchas.mydomain.com.
Thiswouldlooklikethis:
$csvValue="computername.mydomain.com"$csvValue.Trim("com")
Theoutputofthisisshowninthefollowingscreenshot:
TheprecedingexampledisplayshowtheTrim()methodwillremovestringsfromthefrontandtheendofastring.Youfirstneedtostartbydeclaringthe$csvValuevariableasequaltocomputername.mydomain.com.YouthenneedtoleveragetheTrim()methodonthevariablesearchingforthewordcom.You’llseethatthemethodtrimsboththebeginningcomandendcomonthestringitself.Theendresultisputername.mydomain.
TheSubstringmethodTheSubstring()methodisanotherstringmanipulatorwithinthePowerShelltoolset.Itisbasedontherequirementthatyoumaywanttoremovecharacterspresentatafixedpositionwithinastring.ThefollowingtabledisplaysthestringpositionsforthestringTESTING123.Likeanarray,thestringpositionstartscountingat0,asshownhere:
Stringposition 0 1 2 3 4 5 6 7 8 9
Stringvalue T E S T I N G 1 2 3
Toobtainasubstringfromastring,executethefollowingcommand:
$string="TESTING123"$string=$string.substring("7")$string
Theoutputofthisisshowninthefollowingscreenshot:
TheSubstring()methodisdesignedtoextractdatapresentatspecificlocationsinastring.Ifyouwantedtoextractthenumbers123fromtheprecedingtable,youcanusetheSubstring()methodreferencingthestartpositionof7.Alloftheremainingcharactersafterposition7willbedisplayedandtheoutputofthemethodis123.
Toobtainasubstringrangefromastring,executethefollowingcommand:
$string="TESTING123"$string=$string.substring("0","4")$string
Theoutputofthisisshowninthefollowingscreenshot:
TheSubstring()methodallowsyoutoenterasecondvaluewithinthemethod.Whilethefirstvaluedesignatesthestartposition,thesecondvaluedesignateshowmanycharactersafterthestartpositionyouwanttoinclude.Inthepreviousscriptexample,thescriptstartsatposition0andcounts4spacesafterthepositionof0.TheresultofthiscommandisTEST.
ThestringtrueandfalsemethodsPowerShellhasbuilt-instringsearchingcapabilitiesthatprovideyouwiththeabilitytoquicklydeterminewhetherastringcontainsaspecificvalue.ThethreemethodsthatcanperformthesearchinginastringareContains(),Startswith(),andEndswith().Allofthesemethodsarebasedonthesameprinciple,thatis,findingaspecificvalueandreportingTrueorFalse.
Toseewhetherastringcontainsavalue,dothis:
$ping=pingThisDoesNotExistTesting.com–r1$ping$deadlink=$ping.contains("Pingrequestcouldnotfindhost")$deadlink
Theoutputofthisisshowninthefollowingscreenshot:
Thisexampleleveragesthepingcommandtodeterminewhetheraspecificwebsiteorhostisalive.Inourexample,youcapturethepingcommandinthe$pingvariable.YouthensearchthatvariablefortextthatmatchesPingrequestcouldnotfindhost.Astheoutputfromthepingcommandreturnsthevalueyouarelookingfor,theContains()methodwillreturnTrueandthe$deadlinkvariableissettoTrue.
Toseewhetherastringstartswithavalue,executethefollowingcommand:
$ping=pingThisDoesNotExistTesting.com–r1$ping$deadlink=$ping.StartsWith("Pingrequestcouldnotfindhost")$deadlink
Theoutputofthisisshowninthefollowingscreenshot:
WhenyourunthesamescriptwiththeStartswith()method,itwillreturnthesameresultofTrue.ThatisbecausethevaluethatyouaresearchingforstartswithPingrequestcouldnotfindhost.
Toseewhetherastringendswithaspecificvalue,executethefollowingcommand:
$ping=pingThisDoesNotExistTesting.com–r1$ping
$deadlink=$ping.EndsWith("Pleasecheckthenameandtryagain.")$deadlink
Theoutputofthisisshowninthefollowingscreenshot:
WhenyourunasimilarscriptwiththeEndswith()method,itwillreturntheresultofTrue.ThatisbecausethevaluethatyouaresearchingforendswithPleasecheckthenameandtryagain.
NumbermanipulationandparsingPowerShellisapowerfulmathematicscalculator.Infact,PowerShellhasanentireWindowsclassdedicatedtomathematicscalculationsthatcanbecalledbyusingthe[System.Math].NETclass.Whenyouareworkingwiththe[System.Math]classes,itiscommontocallstaticfieldswithinaclass.Staticfieldsarestaticproperties,methods,andobjectsthatcanbecalledtodisplaydataordoactions.Tocallastaticfield,youcallthe[Math](shortenedversionof[System.Math])class,followedbytwocolons::andthestaticfieldname.
Tousethemathoperationtocalculatepi,executethefollowingcommand:
[math]::pi
Theoutputofthisisshowninthefollowingscreenshot:
ThissimplecommandwillprovidePIifyoueverneeditforacalculationbyusingthepimethodofthemathclass.Theresultofthiscommandreturns3.14159265358979.
TousethemathoperationtocalculateEuler’snumber,executethefollowingcommand:
[math]::e
Theoutputofthisisshowninthefollowingscreenshot:
Likewise,ifyoueverneedtoreferenceEuler’sNumber(e),youcanachievethisbyleveragingtheemethodofthemathclass.Theresultofthiscommandreturns2.71828182845905.
Tocalculatethesquarerootofanumber,executethefollowingcommand:
[math]::sqrt("996004")
Theoutputofthisisshowninthefollowingscreenshot:
Ifyouneedtocalculatethesquarerootofalargenumber,youcanusethesqrtmethodofthemathclass.Theresultofthiscommandreturns998.
Toroundanumber,executethefollowingcommand:
$number="214.123857123495731234948327312341657"[math]::Round($number,"5")
Theoutputofthisisshowninthefollowingscreenshot:
Roundingisverycommonforintegersinyourscripts.WhenyouwanttousetheRound()method,you’llhavetospecifyanumberandthenumberofdigitsyouwanttorounditto.Inthiscommand,youtakethenumberof214.123857123495731234948327312341657androundittothefifthdigit.Theresultofthiscommandreturns214.12386.
FormattingnumbersWhilePowerShellcanperformmathematicsverywell,itdoesnothaveanynativecommandsfortheformattingofnumbers.Inordertoformatnumbers,you’llneedtoleveragePowerShell’sabilitytousethe.NETFramework’sformattingmethods.Theconstructforthe.NETFrameworkformatmethodsiscalledbyspecifying"{StartingCharacter:FormatTypePrecision}"–f$variable.Thestartcharacteristhepositionwhereyouwanttostartformattingthenumber.Themostcommonformattypesarecurrency(C),decimal(D),numeric(N),percentage(P),andhexadecimal(X).Theprecisionfieldisthenumberofdecimalplacesyouwantthenumbertobeaccurateto.
Toformatyournumberinanumericformatting,executethefollowingcommand:
$number=12375134.132412"{0:N4}"–f$number
Theoutputofthisisshowninthefollowingscreenshot:
Inthisexample,youaretakingthe12375134.132412numberandformattingitinnumericformatstartingatthefirstcharacter.Thiscommandalsoroundsthenumbertothefourthdigit.
Toformatanumbertomakeithexadecimal,executethefollowingcommand:
$number=12375134$number="{0:X0}"–f$number$number
Theoutputofthisisshowninthefollowingscreenshot:
Ifyouwanttoconvertanintegertohexadecimal,youcanformattheintegertohexadecimalbyspecifying"{0:X0}"–f$number.TheoutputofthiscommandisBCD45E.Itisimportanttorememberthathexadecimalonlysupportsformattingfromwholenumbers.Ifyoudonotusewholenumbers,thescriptwillfailduetoitbeinginaninvalidformat.
FormattingbytesPowerShellhastheabilitytodirectlyconvertnumberstokilobytes(KB),megabytes(MB),gigabits(GB),andterabytes(TB)throughpredefinedaliasesforconversions.Thisishelpfulwhenyouarepullingdatavalues,whichbydefault,areformattedinbytes.Someofthesemayincludediskspaceandmemoryonasystem.Theuseofthealiasisnumberinbytesdividedbyoneunitofmeasure.
ToformatbytestoKB,MB,GB,andTB,usethefollowingoperations:
#16GBofMemoryinBytes$ComputerMemory=16849174528$ComputerMemory/1TB$ComputerMemory/1GB$ComputerMemory/1MB$ComputerMemory/1KB
Theoutputofthisisshowninthefollowingscreenshot:
Whenyouexecutetheprecedingscript,PowerShellwilltakethememorysizeofacomputerinbytesandconvertittoterabytes,gigabytes,megabytes,andkilobytes.Asyoucansee,PowerShellprovidesaquickabilitytodeterminedatacalculationsusingthepredefinedaliases.
DateandtimemanipulationWhenyouarescripting,therearetimeswhereyoumayneedtogetthedateandtimeofasystem.PowerShellofferstheget-datecmdlet,whichprovidesthedateandtimeinmanydifferentformatsofyourchoice.
Toobtainthedateobject,executethefollowingcommand:
$time=get-date$time
Theoutputofthisisshowninthefollowingscreenshot:
Thestandardget-datecmdlet,withoutanytriggers,willgeneratethelongdateandtimeformat.Whenyoustorethedateobjectinavariable,itisimportanttorememberthatthedatacapturedfromthecmdletisasnapshotintime.You’llhavetocalltheget-datecmdletagaintogetnewvaluesfortheupdateddateandtime.
Thefollowingtabledisplaysallofthedatetimeformattingcodes:
Formatcode Result Example
MM Monthinnumericformat 04
DD Dayinnumericformat 15
YYYY Yearinnumericformat 2014
HH Hourinnumericformat(24hrs) 14
hh Hourinnumericformat(12hrs) 02
mm Minutesinnumericformat 15
ss Secondsinnumericformat 12
tt AM/PM(12hr) PM
Whenyoucalltheget-datecommand,youalsohavetheabilitytoformatitinmultiplewaysusingthe–formatproperty.Theprecedingtabledisplaysdifferentformattingoptionsyoucanusetocreateyourowndatetimeformat.Thesevaluesarecase-sensitive.
Toformatthedateobjecttospecificvalues,executethefollowingcommand:
$date=get-date–format"MM/dd/yyyyHH:MM:sstt"$date
Theoutputofthisisshowninthefollowingscreenshot:
Thepreviouscommanddisplayshowyouleveragetheget-datecmdletwiththe-formattrigger.Whenyouexecutethecommand,itreturnsthevaluesforthemonth,day,year,hours,minutes,seconds,andtheAM/PMindicator.Asyoucansee,youcanleveragethedatetimeformattinginconjunctionwithstringsandothercharacterstocreatethetimeformatyoudesire.
Toformatthedateobjectandinsertitbetweenstrings,youcanexecutethefollowingcommand:
$date=get-date–format"MMddyyyyHHMMss"$logfile="Script"+$date+".log"$logfile
Theoutputofthisisshowninthefollowingscreenshot:
Theprecedingexampledisplayshowyoucanleveragetheget-datecmdlet,withthe-formattriggertogenerateanameforalogfile.ThisishelpfulinsituationswhereyoumayhavetorunacommandinPowerShellfrequently,andyouhavetolabeltheexecutiontime.Theprecedingscriptwillgeneratethedateandtime,appendthewordScriptinfront,and.logattheendofthestring.Theresultingfilenamefromthisisunique.
Toadddaysusingthedateobject,executethefollowingcommand:
$date=(get-date).AddDays(30).ToString("MM/dd/yyyy")$date
Theoutputofthisisshowninthefollowingscreenshot:
Theget-datecmdletisalsorobustenoughtobeabletoperformmathoperationswithdates.Theprecedingexamplewilltakethecurrentdate,add30daystoit,andsetittothe$datevariable.YoucanalsouseAddYears(),AddMonths(),AddHours(),AddSeconds(),AddMilliseconds(),andAddTicks()toincreasethetime.Ifyouwanttousesubtraction,youcanenteranegativevalueinthemethodanditwillsubtractthatvaluefromthemethods.ThiswouldlooklikeAddDays(-30)tosubtract30days.
NoteFormoreinformationondatetimeformattingvalues,youcangotohttp://technet.microsoft.com/en-us/library/ee692801.aspx.
Thelastformattingtechniqueimportantforscriptingisconvertingsystemtime/tickstolegibletimeformats.Thisisachievedbycallingthe[DateTime]classandleveragingtheFromFileTimemethod.Theprecedingexampledisplaysformattingtheticknumberof130752344000000000,leveragingthe[DateTime]class,andformattingittoMonday,May04,20151:33:20PM.ThisisusefulforsystemattributesthatareonlydisplayedintickformatsuchasLastLogonTimestamporLastBootUpTime.
Toconvertfiletimetoadifferentformat,executethefollowingcommand:
$date=[datetime]::FromFileTime("130752344000000000")$date
Theoutputofthisisshowninthefollowingscreenshot:
Theprecedingexampledisplayshowtotakesystemticksandconvertthemintoalegibledatetimeformat.Youfirststartbydeclaringa$datevariable.Youthencallthe[datetime]classandreferencetheFromFileTimestaticfiled.Youfeedtheticktimeof130752344000000000intothestaticfiled.Thisformatstheticktimetothedefaultdatetimeformatandstoresthevalueinthe$datevariable.Youthencallthe$datevariable,andyouseetheconvertedvalueofMonday,May04,20151:33:20PM.
http://technet.microsoft.com/en-us/library/ee692801.aspx
ForcingdatatypesWhiledevelopingscripts,youmayrunintoinstanceswhereyoumaywanttoforceaspecificdatatype.ThisishelpfulincaseswherePowerShellautomaticallyinterpretstheoutputfromacommandincorrectly.Youcanforcedatatypesbytheuseofbracketsspecifyingadatatypeandavariable.
Toforceastringdatatype,executethefollowingcommand:
[string]$myString="ForcingaStringContainer"$myString
Theoutputofthisisshowninthefollowingscreenshot:
Theprecedingcommandforcesthestringdatatypetothe$myStringvariable.Theresultisthatthe$myStringvariablewillalwaysremainastring.Itisimportanttoknowthatiftheobjectoritemthatyouaretryingtoforcetoadatatypedoesn’thaveadirectconversiontothatdatatype,itwillthrowanerrororexception.Thiswouldbethecaseifyoutrytoinsertastringintoanintegerdatatype.
Toforceastringdatatypeandgenerateadataexception,executethefollowingcommand:
[int]$myInt="TryingtoPlaceaStringinanIntContainer"
Theoutputofthisisshowninthefollowingscreenshot:
Theprecedingexampledisplaystryingtoinsertastringintoan[int]datatype.Youfirststartbyforcingthe$myIntvariabletobea[int]datatype.Youthentrytosetthatequaltoastringvalueof"TryingtoPlaceaStringinanIntContainer".Afterenteringthecommand,youimmediatelyreceiveanexceptionofCannotconvertvalue"TryingtoPlaceaStringinanIntContainer"totypeSystem.Int32.Thisexampleshowsthatyoucannotmixandmatchdatatypesthatdonothavedirectconversionstoeachother.
ThereareavarietyofdatatypesthatyoucanforcewithinPowerShell.ThefollowingtablerepresentsthecommondatatypesforusewithPowerShellandanexplanationandanexampleofitsuse:
Datatype Explanation Example $avalue
[string] StringofUnicodecharacters [string]$a="Hello" Hello
[char] AUnicode16-bitcharacter [char]$a=0xA9 ©
[byte] An8-bitcharacter [byte]$a=0x0001D 29
[int] 32-bitinteger [int]$a=12345 12345
[long] 64-bitinteger [long]$a=1234.243 1234
[bool] BooleanTrue/Falsevalue [bool]$a=1 True
[decimal] A128-bitdecimal [decimal]$a=1234.243 1234.243
[single] Asingle-precision32-bitnumber[single]$a=1234.243 1234.243
[double] Adouble-precision64-bitnumber[double]$a=1234.243 1234.243
[datetime] Adatatimevalue [datetime]$a="01-APR-2014" Tuesday,April1,201412:00:00AM
[xml] AXML-styledvalue[xml]$a="Testing"
$a.test.aTesting
[array] Anarray-styledvalue [array]$a=1,2,31
2
3
[hashtable] Ahashtable-styledvalue [hashtable]$a=@{"Old"="New"}Name
--------
Old
Value
--------
New
PipingvariablesTheconceptofpipingisn’tanythingnewtothescriptingworld.Piping,bydefinition,isdirectingtheoutputofanobjecttoanotherobject.WhenyouusepipinginPowerShell,youaretakingtheoutputofonecommandandsendingthedataforusewithanothersectionofcode.Themanipulationcanbeeithertoamorelegibleformat,orcanbebyselectingaspecificobjectanddiggingdeeperintothoseattributes.Apipeisdesignatedbythe‘|‘symbolandisusedafteryouenteracommand.Theconstructofapipelookslikethis:command|ResultManipulation|SortingObjects.Ifyouneedtoaccesstheindividualitemsinthepipeline,youcanleveragethepipelineoutput$_command.Thistellsthepipelinetoevaluatetheresultsfromthepipelineandtheirattributes.
Thepipelineoffersawidevarietyofuses;youcanleveragecommandssuchassort-objecttosortbyaspecificattribute,format-listtoformattheobjectsintoalist,andeventheselect-objectwhereyoucanselectspecificattributestoformthepipelineforadditionalprocessing.Select-objectalsoallowsyoutoleveragethe–firstand–lastparameterswithanumbertoselectarecordsetfromthebeginningorendingofthepipeline.Anotherpopularcommandisthewherecommand,whichallowsyoutowriteanexpressiontoselectitemsinthepipelinethatmeetcertaincriteria.
Topipevaluesfromacmdlet,executethefollowingcommand:
$services=get-service|where{$_.name–like"*Event*"}|Sort-objectname$services
Theoutputofthisisshowninthefollowingscreenshot:
Thisexampledisplaystheuseofpipingtheget-servicescmdlet.Itstartsbygettingalltheservicesonasystem,theuserthenpipesthoseresultstotheselectioncriteriawheretheobject’snameislikethewordevent,whichthenpipesthoseresultstothesortingofobjectsinalphabeticalorderbytheirnameproperty.TheoutputisonlytheserviceswiththenamesthatcontainEventinalphabeticalorder.
Toobtainallfilesthatarelargerthanaspecificsize,executethefollowingcommand:
$largeFiles=get-childitem"c:\windows\system32\"|where{$_.length–gt20MB}$count=$largeFiles.countWrite-host"Thereare$countFilesover20MB"write-host"FilesOver20MBinc:\Windows\System32\:"$largefiles|select-objectname,length,lastwritetime|format-list
Theoutputofthisisshowninthefollowingscreenshot:
Whenyouleveragethepipecommand,youhavetheabilitytofindspecificdatapertainingtoanobject.Inthisexample,yousearchallofthefilesinc:\windows\system32todeterminewhetherthereareanyfilesthathaveasizegreaterthan20MB.Youwereabletopipetheget-childitemcmdlettothewhereoperatorwiththeselectioncriteria$_.lengthisgreaterthan20MB.Theseresultswereplacedinthe$largeFilesvariable.Fromthere,youusethecount()methodtocountthenumberoffilesthatarelargerthan20MB.YouthenprinttoscreenthetextThereare$countfilesover20MB.YoualsoprinttothescreenFilesover20MBinc:\Windows\System32\:toprovidetextforthefollowingpipedcommand.Youthenneedtotaketheresultsinthe$largeFilesvariableandpipetheresultstotheselect-objectcommandtoselectthename,length,andlastwritetime.Finally,youpipethoseresultstotheformat-listcommand,whichprovidesaformattedlistofresults.
SummaryThischapterexploresthemanymethodsyoucanusetomanipulateandparsedatawithPowerShell.Youlearnedtechniquesthatwillhelpyoubetterworkwithdataandprovidearicherexperienceforindividualsusingyourscripts.
Thestringmanipulationsectiontaughtyoumanydifferentmethodstoworkwithstrings.Thisincludedchangingthecase,splittingandreplacingstrings,countingandtrimmingstrings,searchingstrings,andviewingsubstrings.ThenumbermanipulationsectiontaughtyouhowtousemathematicaloperationswithinPowerShell.Thissectiondisplayeddifferentwaystoformatnumbers,roundnumbers,andcalculatingcomplexmathematicaloperations.Thedatetimesectionofthischapterprovidedyouwithtoolstousewhenyouneedtogatherdateandtimeinformationfromasystem.Youlearnedhowtoformattheget-datecmdlet,manipulatetheresults,andaddorsubtractfromdatevalues.
Thischapteralsoexploredtheforcingofdatatypeswhileworkingwithvariables.Thissectionprovidedexamplesofdifferentdatatypesthatareavailabletouse,andprovidedanexampleonhowtoforceaspecificdatatype.Youthenwrappedupwithanexplanationonpipingandhowtoconstructproperpipingclauses.Itexploredhowtoleveragepipingtosortdataafteraresultisreturnedandprovidedexamplesofpipingwithandwithoutadatasort.
DataparsingandmanipulationisessentialtosuccessfulscriptingwithPowerShell.Withoutusingthesemanipulationtechniquesinthischapter,youmaybeoverlycomplicatingyourscripts.Whileitmaytaketimetofullylearnthesetechniques,it’sessentialtobecomeagoodPowerShellscripter.Inthenextchapter,you’lllearnhowthemanipulateddatayougeneratecanbecorrelatedtoseewhetheritmatchescertaincriteria.You’lllearnthatthecomparisonsaredonewiththeuseofcomparisonoperators.
Chapter3.ComparisonOperatorsPowerShellcomparisonoperatorsareusedtovalidatedatapresentwithinyourscripts.Theseoperatorsenableyoutocomparedataandexecutecodebasedonthedata.ThismakesPowerShellanextremelyeffectivetooltouseforprocessingcomplicateddatawiththeavailablecomparisonoperators.
Inthischapter,youwilllearnthefollowingconcepts:
ComparisonoperatorbasicsEqualandnotequalcomparisonoperatorsGreaterthanandlessthancomparisonoperatorsContains,like,andmatchcomparisonoperators-AND/-ORcomparisonoperatorsBestpracticesforcomparisonoperators
ComparisonoperatorbasicsWhenyouareusingcomparisonoperators,youarecreatingexpressionsthatevaluatetoeitherTrueorFalse.Inprogramming,thisisknownasBoolean.Inthesimplestform,youareaskingPowerShelltoevaluatesimilaritiesordissimilaritiesbetweentwoitems.Basedonthefindingsfromthatexpression,itwillreturnTrueorFalse.WhenthewholeexpressionreturnsFalse,PowerShelldoesn’tcontinuetoprocessitemsinthestatement.WhenthewholeexpressionreturnsTrue,PowerShellwillproceedforwardintothestatementandexecutethecodewithinthestatement.
Ofthemanybuilt-invariablesthatPowerShellhas,therearetwobuilt-inBooleanvariables.Thesetwovariablesare$Trueand$False.Whenyoucall$True,itimpliesthatthevalueisBooleanandissettoTrue.Whenyoucall$False,itimpliesthatthevalueisBooleanandissettoFalse.
Ascriptthatshowshowtousebasiccomparisonoperatorswouldlooklikethis:
$TrueVariable=$True$FalseVariable=$Falseif($TrueVariable){Write-Host"StatementisTrue."}if($FalseVariable){Write-Host"StatementisFalse."}
Theoutputofthiscommandisshowninthefollowingscreenshot:
ThisexampledisplayshowtodoabasicBooleancomparison.Youfirststartbydeclaring$TrueVariableandsettingitequaltoTrue.Youthendeclare$FalseVariableandsetittoFalse.Youthencreateanifstatementtoevaluatetheexpression$TrueVariabletoseewhetheritevaluatestoTrue.SincethevariableissettoTrue,itwillevaluatetoTrueandcontinuetoprocesstheremainingitemsinthestatement.PowerShellwillprinttothescreenthemessageStatementisTrue.Youthencreateanotherifstatementtoevaluatetheexpression$FalseVariabletoseewhetheritevaluatestoTrue.AsthevariableissettoFalse,theexpressionwillevaluatetoFalseandstopprocessingthestatement.
EqualandnotequalcomparisonThemostbasicandmostusedcomparisonoperatorisequalto(-eq).Thisoperatorisflexibleinnatureasitcanbeusedforstrings,integers,andobjects.The-eqoperatorisusedbycallingvalue1isequaltovalue2.Whenthe–eqoperatorevaluatesthestatement,itwillreturnaBooleanvalueofeitherTrueorFalse.IftheexpressionevaluatestobeTrue,PowerShellwillcontinuetoproceedtoexecutethecode.
Ascriptthatshowshowtouseequalcomparisonoperatorswouldlooklikethis:
$value1="PowerShell"$value2="PowerShell"if($value1–eq$value2){Write-Host"It'sEqual!"}
Theoutputofthisisshowninthefollowingscreenshot:
Fromtheprecedingexample,youwillseethattheequalcomparisonoperatordeterminesthat$value1isequalto$value2anditwritestothescreenIt'sEqual!.Intheinstancethatyouwanttodeterminewhethertwovaluesarenotequal,youcanusethe–neoperator.Thisdoestheinverseofthe–eqoperator.
Ascriptthatshowshowtousenotequalcomparisonoperatorswouldlooklikethis:
$value1="PowerShell"$value2="POSH"if($value1–ne$value2){Write-Host"ValuesAreNotEqual"}
Theoutputofthiscommandisshowninthefollowingscreenshot:
Whenyouruntheprecedingscript,PowerShellwilldeterminethat$value1and$value2arenotequal.ThescriptwillwritetothescreenthemessageValuesAreNotEqual.Whilescripting,itisimportanttominimizetheuseofthenotequal–neoperator.Whenyoustartlayeringisequaltoandnotequaltoinyourscripts,thelogicalcomplexityofthescriptsignificantlyincreases.Thisiswhyitisrecommendedthatbeginnersshouldtypicallyonlyusethe–neoperatorininstanceswhereavaluecannotequalaspecificvalueandeveryothervalueisacceptable.
Ascriptthatshowshowtouse“notequal”comparisonoperatorswouldlooklikethis:
$value="Thisisavalue."$length=$value.length
If($length–ne0){Write-Host"Thevariablehasdatainit.Dothisaction"}
Theoutputofthiscommandisshowninthefollowingscreenshot:
Theprecedingexampledisplaystheproperuseofthe–neoperatorforbestpractices.Thisscriptcountsthecharactersin$value,andifthelengthofthevariableisnotequalto0,thescriptwillwritetotheconsoleThevariablehasdatainit.Dothisaction.Inyourscripting,youwillwanttofollowsuitwhereyouuse–neforverificationthatthedataisnotvalidbeforecontinuingwithyourscript.
GreaterthanandlessthancomparisonPowerShellhastwooperatorstocomparetwovaluestodeterminewhethertheyaregreaterthan(–gt)orlessthan(-lt)eachother.Thisisnotjustlimitedtonumbers,butalsohastheabilitytocomparedatesandtimesaswell.Thesearehelpfulininstanceswhereyouneedtocomparefilesizesormodificationdatesonfiles.
Ascriptthatshowshowtousethe“lessthan”comparisonoperatorwouldlooklikethis:
$number1=10$number2=20If($number1–lt$number2){Write-Host"Value$number1islessthan$number2"}
Theoutputofthiscommandisshowninthefollowingscreenshot:
Intheprecedingexample,yousetthe$number1variableto10andthe$number2variableto20.Youthenusethe“lessthan”(–lt)operatortodeterminewhetherthe$number1variableislessthan$number2.Sincethisatruestatement,theconsoleoutputsthemessageValue$number1islessthan$number2.
Ascriptthatshowshowtousethe“greaterthan”comparisonoperatorwouldlooklikethis:
$olddate=Get-DateStart-Sleep–seconds2$newdate=Get-DateIf($newdate–gt$olddate){Write-Host"Value$newdateisgreaterthan$olddate"}
Theoutputofthiscommandisshowninthefollowingscreenshot:
Inthisscript,youstartbysettingthe$olddatevariabletothecurrentdateandtime.Thestart-sleepcmdletisthenusedtopausethescriptfor2seconds.Whenthescriptcontinues,youset$newdateandtimevariableto2secondslater.Byusingthegreaterthan(-gt)operator,youdeterminethatthevaluesaredifferentandthatthe$newdatevalueisgreaterthanthe$olddatevalue.
TipInadditionto“greaterthan”and“lessthan”operators,youalsohavetheoptionto
compare“greater”or“equal”(-ge)and“less”or“equal”(-le).Thesecomparisonoperatorscanbehandywhencreatingcountersorloopsthatrequireyoutoincrementanumberuntilitequalsorisgreaterthanaspecificvalue.
Contains,like,andmatchoperatorsThe-contains,-like,and-matchoperatorsareverysimilarinfunction.Whiletheyallcomparedata,theyallhavetheirownpurposeinyourscripts.Eachoftheseoperatorsarecase-insensitive.Thismeansthatwhenyouaresearchingforitemsusingtheseoperators,theywillmatchallinstancesofthevalueintheexpression.Ininstanceswhereyouneedthesearchtobecase-specific,youcanappendcinfrontoftheoperatortoforcecasesensitivity.Thesewouldlooklike–ccontains,-clike,and–cmatch.Toforcecaseinsensitivity,youcanalsoappendiinfrontoftheoperator.Thesewouldlooklike–icontains,-ilike,and–imatch.
Eachoftheseoperatorsalsohasaninverseoperatorthatisformedbyappendingtheword“not”infrontoftheoperator.Examplesoftheseoperatorsinclude–notcontains,-notlike,and-notmatch.Youmayalsoappendcasesensitivityandcaseinsensitivitytotheseoperators.
The-containsoperatorlooksforanexactmatchtoavalueinanexpression.ItwillthenreturnaTrueandFalseresult.The–containsoperatorisflexibleasitcanevaluatetheindividualvaluesinanarraywithasingleexpression.Thisallowsyoutocreateefficiencyinyourcodebyevaluatingmorethanoneitemperlineofcode.
Ascriptthatshowshowtousethe-Containscomparisonoperatorwouldlooklikethis:
$myarray="this","is","my","array"If($myarray–contains"this"){Write-Host"Thearraycontainstheword:this"}If($myarray–notcontains"that"){Write-Host"Thearraydoesnotcontaintheword:that"}
Theoutputofthiscommandisshowninthefollowingscreenshot:
Intheprecedingexample,youcreateanarraywithfourvaluesinit.Youthenusethe–containsoperatortodeterminewhetherthearrayhasthethisvalue.Asthearraydoeshavethisvalue,itthenevaluatesthestatementtobeTrue,andproceedstowritetotheconsolethemessageThearraycontainstheword:this.Thesecondpartofthisevaluationistochecktoseewhether$myarraydoesnotcontainthewordthatbyusingthe–notcontainsoperator.Since$myarraydoesnothavethewordthat,itproceedstowritetotheconsoleThearraydoesnotcontaintheword:that.
The-likecomparisonoperatorisdifferentthanthe-containsoperator.The–likeoperatorrequiresthatbothsidesoftheexpressionshouldbeevaluatedtomatchthefullstring.Youcanquicklydeterminewhethertherearevaluesthatareclosetoavalueyouarelookingfor,whichwillthenreturnTrueorFalse.Thisiswhythe–likecomparison
operatortypicallyuseswildcardcharactersdesignatedbyanasterisk(*)orquestionmark(?).Itprovidestheflexibilitytoquicklysearchavarietyofvaluesusingasingleexpression.Theasteriskwildcarddesignatesthattheexpressioncanmatchanyvaluesbeforeorafterthestatedword,dependingonwheretheasteriskisplaced.Thequestionmarkallowsyoutomatchanyvaluespresentbetweentwostrings.Forexample,youcanuse–like"myfile?.txt",whichwillmatchanyvaluethatstartswithmyfileandendswiththeextension.txt.AnyvaluesbetweenthosecharacterswillbereturnedasTrue.
Ascriptthatshowshowtousethe–likecomparisonoperatorwouldlooklikethis:
$myexample="ThisisaPowerShellexample."If($myexample–like"*shell*"){Write-Host"Thevariablehasawordthatislikeshell"}If($myexample–notlike"*that*"){Write-Host"Thevariabledoesn'thaveawordthatislikethat"}
Theoutputofthiscommandisshowninthefollowingscreenshot:
Theprecedingscriptdisplaysthestring$myexample,forwhichyousearchforthevalueofshell.Asthevalueispartofanotherword,youneedtoappendthewildcardcharacteronbothsidesoftheword“shell”.Whenyousearchfortheword*shell*,includingthewildcardcharacters,theresultreturnstrue.TheconsolethenoutputsthemessageThevariablehasawordthatislikeshell.Whenyouexecutethesecondcomparisonusingthe–notlikeoperator,youareabletosearchthestringforwordsthatarenotlikethat.Sinceyouusethewildcardsoneachsideoftheword,itdoesasecondarycomparisontomakesurethattherearen’tpartialvaluesinthevariablethatreflectthat.Sincetherearenovaluesinthevariablethatevaluatetobelikethat,itoutputstothescreenthemessageThevariabledoesn'thaveawordthatislikeshell.
TipYouhavetouseanasterisk(*)onbothsidesofthesearchevaluationcriteriaasPowerShellinterpretseverycharacterinthesentenceasavalue.Whileinherentlyyoumaybreakaparteachwordinthevariableasseparatevalues,PowerShellseesitasonecontiguousgroupofcharacters.Tofindasubstringofavariableandhaveitevaluateto“True”usingthe–likeoperator,youwillneedtouseanasterisk(*)onbothsides.
Thematchcomparisonoperatorusesregularexpressionstomatchinformationbetweentwovariables.The-matchoperatorisuniqueinthefactthatitautopopulatesavariablenamed$matcheswiththewordthatmatchesyoursearch.Thisishelpfulintheinstancewhereyouneedtoonlyretrieveobjectsthatmatchacertaincriteria.With“match”,youcanalsoleveragetheuseofregularexpressionstomatchcriteriatoavariable.
Ascriptthatshowshowtousethe–matchand-notmatchcomparisonoperatorswouldlooklikethis:
$myexample="Thenetworkwentdown."If($myexample–match"[o]"){Write-Host"Thevariablematchedthelettero.(Containstwoo's)"}$matchesIf($myexample–notmatch"[U]"){Write-Host"ThevariabledoesnotmatchU.(Doesn'thaveaU)"}
Theoutputofthiscommandisshowninthefollowingscreenshot:
Theprecedingexamplecreatesanewvariablenamed$myexamplewiththestringvalueofThenetworkwentdown..Youthencomparethe$myexamplevariabletotheregularexpression[o]oronethatcontainsaninstanceofotoseethatit’samatch.Sinceoexistsatleastoncecontainedin$myexample,theexpressionreturnsTrueandtheconsoleoutputsthemessageThevariablematchedthelettero.(Containstwoo's).Afteryoumakethatcomparison,youthendisplaythecontentsofthe$matchesvariable.Youwillseethatthe$matchvariableautopopulateswiththevalueofanindexof0andnameofo.Thelastpartofthescriptisanevaluationtoseewhether$myexampledoesnotmatchtheregularexpressionof[U]ordoesnotcontainaninstanceofU.SincethevariabledoesnotcontainaninstanceoftheletterU,itevaluatestobeTrueandwritestotheconsolethemessageThevariabledoesnotmatchU.(Doesn'thaveaU).
And/ORcomparisonoperatorsThe–andand–orcomparisonoperatorsareusedtoevaluatemultipleexpressionspresentwithinasinglelineofcode.TheseareusedtoseewhethertwoormoreexpressionsevaluatetobeTrue.The–andcomparisonoperatormandatesthatbothevaluationsmustevaluatetobeTruetoproceedinthestatement.Thismeansthatexpression1andexpression2mustbeTruetocontinue.The–orcomparisonoperatoronlyrequiresoneofthetwoexpressionstobeTrue.Thismeansthatexpression1orexpression2canbeTruetocontinue.AsyouarelearningPowerShell,youwillwanttousecautionwhileusingthe-andand-orcomparisonoperatorsastheycanquicklycomplicatethelogicofyourscripts.
Ascriptthatshowshowtouse–andand-orcomparisonoperatorswouldlooklikethis:
$myvar=$True$myothervar=$FalseIf($myvar–eq$True–AND$myothervar–eq$False){Write-Host"BothstatementsevaluatetobeTrue"}If($myvar–eq$True–OR$myothervar–eq$True){Write-Host"AtleastonestatementevaluatestobeTrue"}
Theoutputofthisisshowninthefollowingscreenshot:
Theprecedingexamplebrieflydisplayshowtousethe–andoperatorandthe–oroperator.Inthisexample,youcreatetwodifferentvariables.Youthenchecktoseewhether$myvarequalsTrue,whichevaluatestobeTrue.Youevaluatewhether$myothervarisequaltoFalse,whichevaluatestobeTrue.Inorderforthe–andoperatortobesuccessful,bothstatementshavetoevaluatetobeTrueintheevaluationcriteria.SinceboththestatementsevaluatetobeTrue,theconsoleoutputsthemessageBothstatementsevaluatetobeTrue.Eventhoughthe$myothervarvariableissettoFalse,theevaluationtoseewhetherthatvariableissettoFalsemakesthatstatementTrue.
Thesecondstatementyouevaluateiswheneither$myvaror$myothervarequalsTruebyusingthe–ORoperator.Likethefirstevaluation,thefirstvariableevaluatestobeTrue.However,thesecondvariableevaluatestobeFalse.Sincethe–oroperatoronlyrequiresoneofthetwostatementstobeTrue,theentirestatementevaluatestobeTrue.TheconsolewilloutputthemessageAtleastonestatementevaluatestobeTrue.
BestpracticesforcomparisonoperatorsPowerShelloffersmanydifferentcomparisonoperatorsforusewithinyourscripts.ItiseasytostartbuildingoverlycomplexscriptsbyoverusingcomparisonoperatorsorbyevaluatingitemsthatyoumaynothavetouseinPowerShellfunctioning.Refertothefollowingguidelinestosticktowhenyouaredevelopingyourscripts.Thesewillhelpyouavoidoveruseofcomparisonoperators:
Assumethescriptisdesignedtoproceed:Whenyouassumeyourscriptisdesignedtoproceedtothenextstep,youcanreducethenumberofcomparisonoperatorsyouuse.IfyouexpectavaluetobeTrue,onlymakeastatementtocatchwhetherthestatementisFalse.Don’tchecktoseewhetherthestatementisTrue,asPowerShellisdesignedtosequentiallyproceedanywaytothenextstep.Avoiddoublenegativestatements:Whenyouaredevelopingyourcode,avoidtheuseofdoublenegativestatements.AvoidcheckingtoseewhetheravaluedoesnotequalFalse.Whatyou’rereallytryingtodoischecktoseewhetherastatementevaluatestobeTrue.Doublenegativescanbeconfusingtoyouandotherdevelopersreadingyourcode.Staypositive(True)whileyou’recoding:Alwaysattempttoavoidtheuseofnotandnegativeevaluationstatements.Whiletherecanbeaplaceforthenotbasedoperators,trytocreatecodethatevaluateswhenstatementsareTrue.Thenotbasedoperatorsgrowsignificantlyincomplexitywhenusedwithregularexpressionsandcanbeconfusingtoyouandotherdevelopersreadingyourcode.
SummaryThischapterexploredthemanymethodswithwhichyoucanusePowerShelloperators.Youstartedbylearningthecomparisonoperatorbasics.Youthenlearnedabouttheequalandnotequalandgreaterthanandlessthancomparisonoperators.Youlearnedthatyoucanusetheseoperatorstocomparenumbers,strings,dates,andtimes.Youthenproceededtoexplorethe-contains,-like,and-matchoperators.Youlearnedthatyoucanaddnottotheseoperatorstocreatetheinverseoftheoperator.Youalsounderstoodthatyoucanaddcforcasesensitivityandiforcaseinsensitivitytothecomparisonoperators.Youalsosawhowtojoinmultipleoperatorsusingthe-and/-oroperators.
Thechapterendsbyprovidingthebestpracticesfortheimplementationofcomparisonoperators.Bytheendofthischapter,youshouldbeproficientinusingcomparisonoperators,knowwhattoavoid,andbewellonyourwaytoevaluatingvariablesandarrays.Inthenextchapter,youwillexplorehowyoucancreatecodethatcanbecalledmultipletimesandleveragecomparisonoperatorswithfunctions,loops,switches,andmethods.
Chapter4.Functions,Switches,andLoopsStructuresWhenyouarescriptinginPowerShell,youwillfindthatalotofyourcodingeffortswillrequirethecodetoberepeatedmultipletimesinthesamescript.Whilerepeatingthesamecodemayhelpyouaccomplishthetask,therearemanyotheroptionsforcodingmoreefficientscripts.Thischapterexploresdifferenttechniquesforwhichyoucanreusecodeinsteadofrepeatingthesamecodesegmentswithinthesamescript.
Inthischapter,youwilllearnaboutthefollowingconcepts:
CreationoffunctionsCreationofloopsCreationofswitchesCombiningtheuseoffunctions,switches,andloopsBestpracticesforfunctions,switches,andloops
FunctionsWhenyouneedtoqueryorexecutecodemorethanonce,thegeneralruleisthatyoushouldcreateafunctiontoperformtheaction.Functionsareblocksofreusablecode,whichyoucanexecutemultipletimesbycallingthefunction’sname.Youmustplaceafunctionnearthebeginningortopofthescript.ThisallowsPowerShelltointerpretthewholefunctionbeforeyouuseitlaterinthecode.Allothercode,includinginvokingthefunctions,shouldfollowthefunctionssection.IfyoucallafunctionthathasnotyetbeenparsedbyPowerShell,itwillthrowanexceptionstatingthatnosuchcmdletorfunctionexists.
Functionnamescanbeanywordorsetofwords;however,itisrecommendedtonamethefunctionsimilartotheverb-nouncmdletnamingsyntax.Tocreateafunction,youneedtousethewordFunctionanddeclareafunctionnamelikedisplay-text.Youthenneedtoenclosetherepeatablecommandsincurlybracketsafterthefunctionname.
Thepropersyntaxofafunctionlookslikethis:
FunctionDisplay-Text{Write-Host"ShowingText"}Display-Text
Theoutputofthiscommandisshowninthefollowingscreenshot:
Thisexampledisplayshowtoproperlydeclareafunction.YoufirstcalltheFunctioncommandwiththeDisplay-Textfunctionname.YouthenplaceWrite-Host"ShowText"inthecurlybracketsafterdeclaringthefunctionname.YouthencallthefunctionbytypingDisplay-Text.Afterexecutingthescript,theconsolewillprinttothescreenthemessageShowingText.
Functionsalsoallowyoutopassindataforprocessing.Oneofthemethodstopassindataintoafunctionistodeclarevariablesafterthefunctionnameinparentheses.Thisfunctionwillthenbeabletousethosevariablesandthedatainthosevariableswithinitself.Ifyouwanttopassinmultipleargumentsintoafunction,youcanseparateeachvariablewithacomma.
Theformattodeclareafunctionwithparametersinparentheseslookslikethis:
FunctionDisplay-Text($variable1,$variable2){Write-Host"FirstFunctionArgument:$variable1"Write-Host"SecondFunctionArgument:$variable2"}Display-Text"Hello""Readers"
Theoutputofthisisshowninthefollowingscreenshot:
Thisexampledisplayshowtoproperlydeclareafunctionwiththeparameterinparentheses.YoufirstcalltheFunctioncommandwiththeDisplay-Textfunctionname.Youthenplacethevariables,$variable1withacommaand$variable2inparentheses,beforethecurlybrackets.Insidethecurlybrackets,youdeclareWrite-Host"FirstFunctionArgument:$variable1"andWrite-Host"SecondFunctionArgument:$variable2".YouthencallthefunctionbytypingDisplay-TextwiththeargumentsofHelloandReaders.Afterexecutingthescript,theconsolewillprinttothescreenFirstFunctionArgument:HelloandSecondFunctionArgument:Readers.
AnothermethodtopassindatatoafunctionisthroughtheuseofaparameterblockofParam.Paramtakesinwhateverdatayoupassintothefunctionandstoresthatdataindeclaredvariables.Ifyouwanttopassinmultipleargumentsintoafunction,youcanseparateeachvariablewithacomma.Whenyouaredeclaringparametersusingthismethod,Paramneedstobethefirstitemdeclaredaftertheopencurlybracketinafunction.
Theformattodeclareafunctionwithparamlookslikethis:
FunctionDisplay-Text{Param($variable1,$variable2)Write-Host"FirstFunctionArgument:$variable1"Write-Host"SecondFunctionArgument:$variable2"}Display-Text"Hello""Readers"
Theoutputofthiscommandisshowninthefollowingscreenshot:
ThisexampledisplayshowtoproperlydeclareafunctionwithparametersinaParamblock.YoufirstcalltheFunctioncommandwiththeDisplay-Textfunctionname.YouthencalltheParamblockasthefirstcommandinsidethecurlybrackets.InsidetheParamblock,youdeclarethevariables$variable1withacommaand$variable2.AftertheParamblock,youdeclareWrite-Host"FirstFunctionArgument:$variable1"andWrite-Host"SecondFunctionArgument:$variable2".YouthencallthefunctionbytypingDisplay-TextwiththeargumentsHelloandReaders.Afterexecutingthescript,theconsolewillprinttothescreenFirstFunctionArgument:HelloandSecondFunctionArgument:Readers.
TheParamblockisspecialasitcanalsoacceptadditionaldecoratorswhendeclaringthevariables.The[Parameter()]decoratorallowsyoutoincludeadditionalargumentsthatenableyoutovalidatevariablesandevenprovidehelpinformationforvariablesinfunctions.WhenyoudeclaretheMandatoryargumentandsetitequalto$True,itwillrequirethatthevariableisusedinthefunctiontocontinue.IfyousettheMandatoryargumentto$False,itwillnotberequiredwhenusingthefunction.YoucanalsocallthePositionargument,whichdeclareswhatpositionthevariablewillbedeclared.ThismeansthatifyousetthePositionargumentto1,itmustbethefirstargumentpassedintothefunction.Ifyoudon’tusethePositionargument,youwillonlybeabletopassinthevariablesusingparameterthatreferencesthevariablename.AnotherpopularargumentistheHelpMessageargument,