13.07.2015 Views

A QUICK-START GUIDE TO POWERSHELL - Windows IT Pro

A QUICK-START GUIDE TO POWERSHELL - Windows IT Pro

A QUICK-START GUIDE TO POWERSHELL - Windows IT Pro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

PowerShell101A<strong>QUICK</strong>-<strong>START</strong><strong>GUIDE</strong><strong>TO</strong><strong>POWERSHELL</strong>byRobert Sheldon


2PowerShell 101: A Quick Start Guide to PowerShell


Lesson 1: Getting What You Need to Create Basic PowerShell Commands 3Lesson 1:Getting What You Need to CreateBasic PowerShell CommandsBy now, most administrators are familiar with <strong>Windows</strong> PowerShell. Many have downloaded it, playedwith it, and perhaps used it to perform ad hoc tasks as they might do in <strong>Windows</strong> command shell (cmd.exe). But PowerShell is a lot more than a simple DOS-like command shell. It’s a command-line andscripting environment that leverages the Microsoft .NET Common Language Runtime (CLR) and .NETFramework. When you work in the PowerShell environment, you’re working with .NET objects. Thefolder structures you view or the services you access are actually instances of objects that represent thefolders and services, unlike other command shells that simply process text. As a result, PowerShell providesfar more power and flexibility than traditional command shells.To help you take advantage of this power, I’ve written a series of lessons that explain how to usePowerShell to perform various tasks. Each lesson builds on previous lessons in order to demonstrateimportant PowerShell concepts. In this lesson, I explain how to get started using PowerShell and howto run basic PowerShell commands. I also show you how to get help within PowerShell when creatingthose commands and how to use aliases in your commands.Getting StartedPowerShell currently doesn’t ship with <strong>Windows</strong> OSs, although this will change starting with <strong>Windows</strong>Server 2008. You can find Power- Shell download links and information on the <strong>Windows</strong> PowerShell Webpage (www.microsoft.com/powershell). Before you download PowerShell, install .NET Framework 2.0 ifyou don’t already have it. The PowerShell installation process is quick and straightforward. Just be sure toinstall the PowerShell edition specific to your OS. Microsoft provides editions for Server 2008 beta 3, <strong>Windows</strong>Vista, <strong>Windows</strong> XP SP2, and <strong>Windows</strong> Server 2003. For this lesson, I’m running PowerShell on XP.After PowerShell is installed, you can use it immediately. To run PowerShell, select All <strong>Pro</strong>gramsunder the Start menu, choose <strong>Windows</strong> PowerShell 1.0, and click <strong>Windows</strong> Power- Shell. When thePowerShell window appears, the command prompt displays the current working folder (C, on mysystem). You’re now ready to start writing and executing PowerShell commands.PowerShell 101: A Quick Start Guide to PowerShell


4 Lesson 1: Getting What You Need to Create Basic PowerShell CommandsWorking with CmdletsPowerShell supports its own scripting language, which is based on the .NET Framework. The most basiccommand in that language is the cmdlet (pronounced command-let). A cmdlet is similar to a function inthat it performs a specific task, such as retrieving a folder’s contents or updating a registry entry.PowerShell includes more than 100 built-in cmdlets. You can create additional cmdlets, but youmust create them in a .NET language, such as Visual Basic .NET or C#. (The Power- Shell 101 serieswill discuss only the built-in cmdlets.) Each cmdlet is in the form verb-noun because Microsoft wantedto use a consistent naming scheme to make PowerShell easy to learn and expand. The verb specifiesthe action to be taken. The noun indicates the type of object involved. For example, the Get-ChildItemcmdlet retrieves a list of items in the current working directory or container, such as the registry. Torun the cmdlet, type it at the PowerShell command prompt and press Enter. The results are displayedbeneath the command prompt. That’s all there is to running a basic command.There will probably be times when you don’t know whether there’s a cmdlet for the task you need toaccomplish or when you can’t remember a cmdlet’s name. You can view a list of all cmdlets by using theGet-Command cmdlet. Figure 1 shows part of this list, which includes the cmdlets’ names and syntax, butnot a description of what the cmdlet does. To get that information, you can use the Get-Help cmdlet.Figure 1: Retrieving a list of cmdletsPowerShell 101: A Quick Start Guide to PowerShell


Lesson 1: Getting What You Need to Create Basic PowerShell Commands 5Getting Help with CmdletsPowerShell includes a set of Help files that you can access directly from the Power- Shell commandwindow with the Get-Help cmdlet. To retrieve Help information about a specific cmdlet, you useGet-Help with its -name parameter followed by the name of the cmdlet you want to learn about. Likeparameters in cmd.exe commands, parameters in PowerShell cmdlets provide information that the cmdletsneed to do their job. Unlike parameters in cmd.exe commands (which might start with a hyphen,a slash, or no symbol at all), parameters in PowerShell cmdlets always begin with a hyphen, which isanother example of PowerShell’s consistent naming scheme.Now let’s take a look at an example to demonstrate how this works. A common system administrator’stask is to read text files. After looking at the list of cmdlets that Get-Command provided, you thinkthe Get-Content cmdlet might do the trick but you aren’t sure. To retrieve Help information about Get-Content, run the commandGet-Help -name Get-ContentAs Figure 2 shows, this command returns a description of the cmdlet and syntax information. Thecommand returns the content of an item, which in this case refers to any type of file in a system.Figure 2: Retrieving Help information about Get-ContentPowerShell 101: A Quick Start Guide to PowerShell


6 Lesson 1: Getting What You Need to Create Basic PowerShell CommandsIn the past, you might have used the For command for batch files or the File- SystemObject objectin a <strong>Windows</strong> Script Host (WSH) script, but in PowerShell, you simply use the Get-Content cmdlet. Youcan retrieve more detailed information about the syntax by adding the -full parameter to the commandGet-Help -name Get-Content -fullNotice that the -full parameter doesn’t take a corresponding value. This type of parameter is called aswitch parameter because it switches the behavior of the cmdlet.Figure 3 shows some of the information returned by this command. (On your computer, you’ll needto scroll or resize your window as necessary to view the entire contents.) The PARAMETERS sectionprovides the information you need to include parameters in your command. Two important categories ofinformation for each parameter are Required and Position.Figure 3: Retrieving the full version of the Help file for Get-ContentPowerShell 101: A Quick Start Guide to PowerShell


Lesson 1: Getting What You Need to Create Basic PowerShell Commands 7The Required category tells you whether the parameter is mandatory or optional. When Required isset to true, you must include the parameter. When Required is set to false, the parameter is optional.The Position category tells you whether a parameter must be named or whether it can be referencedby its position. When Position is set to named, you must include the parameter’s name when referencingthat parameter. When Position is set to a number, you can reference the parameter by its name or youcan simply provide the parameter’s value in its correct position.For example, as you can see in Figure 3, the -path parameter is required for Get-Content. However,you can include that parameter value in the first position without including the parameter name, as inGet-Content c:\sample.txtIf a parameter value contains spaces, you must enclose the value in quotes.In the PARAMETERS section, each parameter name is followed by information in angle brackets (). This information specifies the type of data that the parameter value must be. As Figure 3 shows, the-path parameter value must be a string. If a set of brackets ([ ]) follow the word string, then a string arrayis permitted as the parameter value.In the case of switch parameters, which don’t take values, the data type will read . For example,Get-Content’s -force parameter is defined with this data type. This parameter overrides restrictions thatmight prevent the command from succeeding. The override occurs only when you include the parameterin your command.One other feature to note about parameters is that PowerShell includes a parameter-name completionfeature. You need to include only enough of the parameter name to distinguish it from other parameters.For example, the commandGet-Content c:\sample.txt -forceis the same asGet-Content c:\sample.txt -foBesides providing the parameter information that you need to build commands, the Help filefor Get-Content includes examples of how to use the cmdlet, helpful tips in the Notes section, andresources where you find additional information. The best part is that Help files are available for all thecmdlets—there are even Help files that discuss general concepts.Getting Help with ConceptsPowerShell includes a set of Help files that provide overviews of various concepts. Each file begins with“about_” and ends with the name of the topic. To view an alphabetical list of the about topics, run thecommandGet-Help about*To view information about a specific topic, you simply include the topic’s full name as a parametervalue. For example, to retrieve the file about flow control, run the commandGet-Help about_flow_controlPowerShell 101: A Quick Start Guide to PowerShell


8 Lesson 1: Getting What You Need to Create Basic PowerShell CommandsFigure 4, shows part of the results you can expect. As you can see, the file provides an overview ofhow to implement flow control in a Power- Shell script.Figure 4: Retrieving Help information about flow controlUsing AliasesSome of the cmdlet names can be quite verbose, an annoying characteristic if you have to continuouslyretype commands. Fortunately, PowerShell supports the use of aliases for referencing cmdlets. An aliasis an alternate name that’s usually much shorter than the actual cmdlet name. PowerShell includes anumber of built-in aliases, and you can create your own aliases.To view the aliases available to your current session, run the Get-Alias cmdlet. Current session refersto your current connection to PowerShell. When you start PowerShell, you start a new session; that sessionpersists until you close PowerShell, which ends your connection. In addition to displaying all builtinaliases and their associated cmdlets, Get-Alias displays any aliases you created in the current sessionand aliases defined in profiles, which are user-defined configuration settings loaded into PowerShellwhenever it starts. (<strong>Pro</strong>files will be discussed in a later lesson.)PowerShell 101: A Quick Start Guide to PowerShell


10 Lesson 1: Getting What You Need to Create Basic PowerShell CommandsMoving ForwardIn this lesson, I introduced you to the fundamental components necessary to begin exploring and usingPowerShell commands, which consist of one or more cmdlets. In the following lessons, you’ll learnmore about how to use these cmdlets and how to create scripts that enable you to leverage Power-Shell’s full capabilities. In the meantime, begin working with cmdlets. Use Power- Shell’s Help file tocreate commands and learn about specific concepts. Try out the different parameters and learn how tocreate and use aliases. In no time at all, you’ll be ready to incorporate PowerShell into your dailyroutines.PowerShell 101: A Quick Start Guide to PowerShell


Lesson 2: How to Create Pipelines and Manage Output 11Lesson 2:How to Create Pipelinesand Manage OutputIn the previous lesson, I introduced you to the concept of cmdlets and how to run basic PowerShellcommands. I also showed you how to use aliases and how to use PowerShell’s Get- cmdlets to get helpwhen creating commands. For example, you can use the Get-ChildItem cmdlet to retrieve a list of itemsin a folder or the Get-Content cmdlet to retrieve the content of a text file. With cmdlets and their parameters,you can run a wide variety commands that display system information or carry out tasks.However, a cmdlet alone might not always provide the full functionality you require. For thisreason, PowerShell lets you create pipelines that link cmdlets together to carry out complex operationsand refine the system information you retrieve. In this lesson, you’ll learn how to link cmdlets into apipeline to create PowerShell statements. You’ll also learn how to format and sort statement output.Implementing a PipelineA PowerShell pipeline is a series of cmdlets that pass objects from one cmdlet to the next. Each cmdletgenerates an object and passes it down the pipeline, where it is received by the next cmdlet. Thereceiving cmdlet uses that object as input and generates its own output as an object. You connect cmdletsinto a pipeline by using the pipe (|) operator.Pipelining in PowerShell is different from pipelining in other command shell environments, such asthe <strong>Windows</strong> command shell. In traditional environments, a command’s results are returned as a singleresult set, which means that the entire result set must be generated before any information is passeddown the pipeline. The first result is returned at the same time as the last result. In PowerShell, however,the results are streamed through the pipeline. As soon as a command returns a result, it passes it downthe pipeline, and that result is immediately available to the next command in the pipeline.Let’s look at an example that will help you understand how a pipeline works. If you run the cmdletGet-ServicePowerShell 101: A Quick Start Guide to PowerShell


12 Lesson 2: How to Create Pipelines and Manage Outputyou’ll receive a list of the services installed your system, similar to the list in Figure 1. Notice that thecmdlet returns the status, name, and display name of each service.Figure 1: Retrieving a list of servicesSuppose you want to retrieve a list of running services only. You can pipe the output from the Get-Service cmdlet to the Where-Object cmdlet, which filters the output based on the specified criteria, asshown in the statementGet-Service |Where-Object {$_.status -eq ‘running’}As you can see, you use a pipe operator to connect the two cmdlets. The Get-Service cmdlet generatesan object that contains the service-related information. The object is passed down the pipeline tothe Where-Object cmdlet. The Where-Object cmdlet receives the object and uses the information asinput. The Where-Object cmdlet filters the information based on the Status property value. Notice thatthe Where-Object cmdlet includes an expression enclosed in braces ({ }). If the expression evaluates totrue, the Where-Object passes that object down the pipeline and filters out any other object.In this case, the Where-Object expression states that the Status property value must be equal to(specified by the -eq operator) the string running. Status is one of the properties available to the objectgenerated by the Get- Service cmdlet. When an object is passed down the pipeline, you can accessits properties, as I’ve done in the Where-Object expression. To access a property in the pipeline in thismanner, you use the $_ built-in variable. This variable holds the current object within the pipeline eachtime the Where-Object cmdlet loops through the pipeline results. You can then reference the object’sproperties, as in $_.Status. The output now looks similar to that in Figure 2. (You’ll learn more about theWhere-Object cmdlet, object properties, and operators in later lessons.)PowerShell 101: A Quick Start Guide to PowerShell


Lesson 2: How to Create Pipelines and Manage Output 13Figure 2: Retrieving a list of running servicesNote that you’d typically enter the statement just given on one line in the Power- Shell consolewindow. However, column widths in the magazine force us to print this statement on more than oneline. Also note in Figure 2 the >> character sequence at the beginning of some of the lines in the command.This character sequence constitutes a multiline prompt. For information about when you’d wantto enter a statement on multiple lines in the PowerShell console window and how to properly do so.Now suppose you want to list only the display name of each running service. You can pipe theoutput of the Where-Object cmdlet to the Select-Object cmdlet:Get-Service |where {$_.status -eq ‘running’} |select displaynameIn this statement, the Select-Object cmdlet receives the object from the Where-Object cmdlet. Inthis case, the statement uses the where alias to reference the Where-Object cmdlet and the select aliasto reference the Select-Object cmdlet. In the select cmdlet, you specify the name of the property (orproperties) that you want to display. For this example, I’ve specified the displayname property. The statementwill now output results similar to those in Figure 3.The key to using pipelines is to remember that you’re always working with objects. Each cmdletgenerates an object that the next cmdlet in the pipeline receives. Even the final cmdlet generates anobject that outputs the statement results. As you progress through the lessons, you’ll learn how to usethose objects and their properties to refine your PowerShell statements.PowerShell 101: A Quick Start Guide to PowerShell


14 Lesson 2: How to Create Pipelines and Manage OutputFigure 3: Retrieving the display names of the running servicesFormatting Statement OutputBy default, PowerShell formats a statement’s output based on the type of data in that output. Forexample, the following statement returns data about the PowerShell process:Get-<strong>Pro</strong>cess powershellIn this case, PowerShell displays the output from this command in a table, as shown in Figure 4.Figure 4: Displaying output in a table formatPowerShell 101: A Quick Start Guide to PowerShell


Lesson 2: How to Create Pipelines and Manage Output 15If you don’t want the output in this default format, you can pipe the statement output to a formatcmdlet. PowerShell supports four cmdlets that format output:• The Format-Table cmdlet displays data in a table (Figure 4). This is the default format for most cmdlets,so you often don’t need to specify it.• The Format-List cmdlet displays data in a list.• The Format-Wide cmdlet displays data in a wide table that includes only one property value for eachitem.• The Format-Custom cmdlet displays data in a custom format, based on stored configuration informationin a .ps1xml format file. You can use the Update- FormatData cmdlet to update a format file. (Adiscussion of the Update-Format- Data cmdlet and format files is beyond the scope of these lessons.See Power- Shell’s “Update-FormatData” Help file for more information.)To change the format of the output from the preceding statement, you can pipe it to the Format-Listcmdlet:Get-<strong>Pro</strong>cess powershell |Format-ListNow your results will be similar to those in Figure 5. Notice that the list format displays only a subset ofthe information displayed in the table format. The information displayed differs between formats.Figure 5: Displaying output in a list formatPowerShell 101: A Quick Start Guide to PowerShell


16 Lesson 2: How to Create Pipelines and Manage OutputPowerShell determines how to format the results based on object type. In other words, the formattype, layout, and properties returned are specific to the type of object. For example, the results returnedby the Get-ChildItem cmdlet when retrieving file system information will be different from the resultsreturned when retrieving information about the registry because they’re two different types of objects,even though the same cmdlet is used. PowerShell uses a set of complex XML format (.ps1xml) files todetermine how to display the results.Controlling Statement OutputWhen you execute a statement, PowerShell applies the default format to the output and sends thatoutput to the console window, unless you override this behavior by using one the four format cmdlets Ijust described. However, you can also control where to send that output. PowerShell provides six cmdletsfor controlling output:• The Out-Host cmdlet sends output to the PowerShell console. This is the default output cmdlet, so youdon’t need to specify it.• The Out-Default cmdlet sends output to the default formatting cmdlet. In addition, Out-Default delegatesthe outputting process to the Out-Host cmdlet. You don’t need to specify the Out-Default cmdlet.• The Out-File cmdlet sends output to a specified file.• The Out-Null cmdlet deletes output and doesn’t send it to the PowerShell console.• The Out-Printer cmdlet sends output to a printer.• The Out-String cmdlet converts the pipeline object to an array of strings. You can find additional informationabout each cmdlet in the PowerShell Help files.To control a statement’s output, add the output cmdlet at the end of your pipeline. For example, thefollowing statement formats the PowerShell process information into a list, then sends that list to the C:\SysInfo\ps.txt file:Get-<strong>Pro</strong>cess powershell |Format-List |Out-File C:\SysInfo\ps.txtWhen you send output to a file, PowerShell saves the content to the file but doesn’t display it inthe console. You can use the Out-File cmdlet to send output to any type of file that makes sense. Forexample, you wouldn’t want to send text to a .bmp file. Although this wouldn’t throw an error, youwouldn’t be able to view anything when you opened the file.The Out- File cmdlet lets you choose whether to append the output to the file or replace the existingcontent with the output. By default, it replaces any existing content. To append the output, you need toadd the -append switch to the Out-File cmdlet:Get-<strong>Pro</strong>cess powershell |Format-List |Out-File C:\SysInfo\ps.txt `-appendPowerShell 101: A Quick Start Guide to PowerShell


Lesson 2: How to Create Pipelines and Manage Output 17Sorting Statement OutputIn addition to formatting output, you’ll often find that you’ll want to sort output. To sort output, you usethe Sort-Object cmdlet. This cmdlet takes the input objects from the pipeline and sorts them based onthe criteria you define. As I mentioned previously, Power- Shell streams the results down the pipelinefrom one command to the next. However, when you sort data, the Sort-Object cmdlet waits until it hasall the results (objects) and then sorts them. This effectively stops the streaming process until everything issorted. For a small result set, this isn’t a problem, but it could impact performance when retrieving largeamounts of data.Still, the Sort-Object cmdlet can be a handy tool. For example, suppose you want to retrieve a list ofthe items in the C:\<strong>Windows</strong> folder. You can use the Get- ChildItem cmdlet in a statement such asdir c:\windows |where {$_.length -gt 500000} |sort -property length-descendingThis statement passes the output object from the Get-ChildItem cmdlet (referenced by the dir alias)to the Where-Object cmdlet (referenced by the where alias). The Where-Object cmdlet specifies that thelength must be greater than (specified by -gt) 500,000 bytes. The results are then passed down the pipeline.When the Sort- Object cmdlet (referenced by the sort alias) has all the objects, it sorts them basedon the defined criteria.In this case, the Sort-Object cmdlet first specifies that the sorting should be based on the Lengthproperty. The -descending switch indicates that the results should be sorted in descending order, asshown in Figure 6. If you don’t specify the -descending switch, the results are sorted in ascending order.In addition, you can specify more than one property (separated by commas) on which to base the sortorder. PowerShell sorts the data first by the first property specified, then by the second, and so on.Figure 6: Sorting data based on property valuesPowerShell 101: A Quick Start Guide to PowerShell


18 Lesson 2: How to Create Pipelines and Manage OutputMoving ForwardAs this lesson demonstrates, the PowerShell pipeline is a powerful feature that lets you combine multiplecmdlets to perform a series of successive operations on one or more objects. You can pipe together multiplecmdlets into a statement, format the output from that statement, specify where to place the output,and even sort the outputted information. In the lessons to follow, you’ll learn how to enhance your statementseven further so you can take full advantage of PowerShell’s pipeline capabilities.PowerShell 101: A Quick Start Guide to PowerShell


Lesson 3: How to Use PowerShell's Operations and Wildcards 19Lesson 3:How to Use PowerShell'sOperations and WildcardsIn PowerShell, you can connect cmdlets together to create a pipeline and use the Where-Object cmdletto filter objects passed down that pipeline. For example, in the following statement, objects from theGet-ChildItem (referenced by the dir alias) cmdlet are piped to a Where-Object cmdlet (referenced bythe where alias), which filters out all items in C:\<strong>Windows</strong>, except those larger than 500,000 bytes:dir c:\windows |where {$_.length -gt 500000}Notice that the Where-Object cmdlet includes an expression that’s enclosed in braces ({ }). Theexpression states that the current value of the Length property must be greater than 500,000. The valueof the Length property is retrieved by using $_.length. The $_ symbol references the current object in thepipeline, and .length retrieves the value of the Length property. The expression then uses the -gt (greaterthan) operator to compare the Length property value to the value of 500,000.As with any language, PowerShell provides a set of operators that let you create expressions you canincorporate into your statements. An expression is a block of code that PowerShell evaluates; the resultof that evaluation determines what action to take. For example, in the preceding statement, PowerShelldetermines whether the Where-Object expression is true or false. When the expression evaluates totrue—that is, the current object’s Length property value is greater than 500,000—that object is passeddown the pipeline and displayed in the output. If the expression evaluates to false—that is, the currentobject’s Length property value isn’t greater than 500,000—the object is discarded and not displayed inthe output.PowerShell includes a variety of operators that you can use in your expressions. This lessondescribes many of those operators and provides examples of how to use them. In addition, the sidebar“How to Find Out a Cmdlet’s <strong>Pro</strong>perties,” discusses how to find property names, such as those used inthe Where-Object expressions in the examples provided.PowerShell 101: A Quick Start Guide to PowerShell


20 Lesson 3: How to Use PowerShell's Operations and WildcardsComparison OperatorsAs the name suggests, comparison operators compare values. When an expression contains a comparisonoperator, PowerShell compares the value to the left of the operator with the value to the rightof it. You saw this idea in the preceding example, in which the Length property value is compared to500,000. PowerShell provides many comparison operators, as Table 1, shows. Let’s examine some ofthose operators to see how they work.Table 1: PowerShell Comparison OperatorsOperator Description Case-sensitiveversion-eq Equal to -ceq -ieq-ne Not equal to -cne -ine-gt Greater than -cgt -igt-ge Greater than or equal to -cge -ige-lt Less than -clt -ilt-le Less than or equal to -cle -ile-like-notlike-match-notmatch-contains-notcontains-replaceUses wildcards to find matchingpatternsUses wildcards to find nonmatchingpatternsUses regular expressions tofind matching patternsUses regular expressions tofind nonmatching patternsDetermines whether value onthe left side of the operatorcontains the value on the rightDetermines whether value onthe left side of the operatordoes not contain the value onthe rightReplaces part or all of the valueon left side of the operator-clike-cnotlike-cmatch-cnotmatch-ccontains-cnotcontains-creplaceExplicit case-insensitiveversion-ilike-inotlike-imatch-inotmatch-icontains-inotcontains-ireplacePowerShell 101: A Quick Start Guide to PowerShell


Lesson 3: How to Use PowerShell's Operations and Wildcards 21The following statement does the opposite of the preceding example; it returns items whose lengthsare smaller than 500,000 bytes:dir c:\windows |where {$_.length -lt 500000}As you can see, the only difference between the two statements is the comparison operator. Thisstatement uses the -lt (less than) operator rather than the -gt operator.Other comparison operators follow the same logic. The following statement uses the -eq (equalto) operator to compare the Responding property value to the string true in order to retrieve a list ofresponding processes:get-process |where {$_.responding -eq ‘true’ }For the Where-Object expression to evaluate to true, the Responding property value must equaltrue. As a result, only responding processes are returned, as Figure 1 shows.Figure 1: Retrieving a list of processesPowerShell 101: A Quick Start Guide to PowerShell


22 Lesson 3: How to Use PowerShell's Operations and WildcardsBy default, all comparison operators perform case-insensitive comparisons. If you want to be moreprecise in your code, you can add the letter i to a comparison operator (e.g., -ieq) to explicitly specify acase-insensitive comparison. However, because this is the default behavior, adding the i isn’t necessary.You can make any comparison case sensitive by adding the letter c to the comparison operator (e.g.,-ceq). For example, the statement‘True’ -eq ‘true’evaluates to true because it ignores case, whereas the statement‘True’ -ceq ‘true’evaluates to false because it takes case into account.I realize that these are very basic examples, but when working in a <strong>Windows</strong> environment, caseoften isn’t a concern because filenames, process names, and other item names are case-insensitive. Butas you become more familiar with PowerShell and learn how to retrieve other types of lists in whichcase-sensitivity is important, you’ll find being able to make an operator casesensitive useful.Another useful PowerShell feature is wildcards. For example, if you don’t know the exact name ofan item when creating an expression to compare values, you can use wildcards in the compared value(the value after the operator). Table 2 describes the wildcards that PowerShell supports.Table 2: PowerShell WildcardsOperator Description Example True (match) False (no match)* Matches zero or moreof any character? Matches any one character[char-char][char…]Matches a range ofsequential charactersMatches any onecharacter in a set ofcharactersab* ab, abc, about againstr?d red, rid, rod bed[a-h]ug bug, dug, hug lug[cft]ool cool, fool, tool poolYou implement wildcards through the use of the -like and -notlike comparison operators. (Notethat -like and -notlike as well as -match, -notmatch, and -replace are sometimes referred to as patternmatchingoperators.) For instance, suppose you want to find all Google-related processes on a computer.You can use the -like operator to return all processes created by companies whose name includes thestring google:et-process |where {$_.company -like “*google*”}PowerShell 101: A Quick Start Guide to PowerShell


Lesson 3: How to Use PowerShell's Operations and Wildcards 23The asterisk wildcard matches zero or more characters, so you’ll receive accurate results no matterwhether the company name is stored in <strong>Windows</strong> as Google, Google Inc., or another variation. Figure 2shows the results from this statement. If you were to use the -notlike operator instead of the -likeoperator, all non-Google processes would be returned.Figure 2: Retrieving a list of Google-related processesIn addition to wildcards, PowerShell supports regular expressions, which are based on the Microsoft.NET Framework regular expression classes. You implement regular expressions through the use of the-match and -notmatch operators. PowerShell’s support for regular expressions is quite extensive— asextensive as you would find in any .NET language. For this reason, a discussion about them is beyondthe scope of this lesson. For information about them, see PowerShell’s about_regular_expression andabout_comparison_ operators Help files.Logical OperatorsSo far, I’ve discussed how to use comparison operators in expressions. When you use one of these operators,you create a condition that’s evaluated to determine whether to take a specific action. However, insome cases, you might want to create expressions that include multiple conditions. In other words, youmight want to perform more than one comparison to determine whether to take that action.To perform multiple comparisons in a single expression,you must use logical operators to link conditionstogether. Logical operators, which are described in Table 3,specify what logic to use when evaluating multiple conditions.Let’s take a look at an example to illustrate how logicaloperators work. The following statement uses the Get- <strong>Pro</strong>cesscmdlet to retrieve a list of running processes:Get-<strong>Pro</strong>cess |where {($_.handles -gt 500) `-and ($_.pm -ne 0)}Table 3: PowerShell Logical OperatorsOperator-and-or-notDescriptionBoth conditions must be true forexpression to evaluate to trueOne or both conditions must be truefor expression to evaluate to trueSpecified condition must be false forexpression to evaluate to true! Specified condition must be false forexpression to evaluate to truePowerShell 101: A Quick Start Guide to PowerShell


24 Lesson 3: How to Use PowerShell's Operations and WildcardsThere are two conditions, each of which is enclosed in parentheses. The first condition ($_.handles-gt 500) specifies that the number of handles must be greater than 500 for a given process. The secondcondition ($_.pm -ne 0) specifies that the paged memory size must not equal 0. The -and logicaloperator connects these two conditions. As a result, both conditions must evaluate to true for the entireexpression (enclosed in braces) to evaluate to true. Only those processes that meet both of these conditionsare returned, as Figure 3 shows.Figure 3: Using the -and operator in an expressionNow let’s take a look at the -or operator. The following statement is the same as the precedingexample except that it uses -or instead of -and:get-process |where {($_.handles -gt 500) `-or ($_.pm -ne 0)}PowerShell 101: A Quick Start Guide to PowerShell


Lesson 3: How to Use PowerShell's Operations and Wildcards 25Figure 4: Using the -or operator in an expressionIn this case, at least one of the conditions must evaluate to true for a process to be included. Inother words, the process must have a handle count greater than 500 or the paged memory size must notequal 0 or both. As a result, many more processes are returned, as Figure 4 shows.You can use the -not logical operator to indicate that a specified condition must not be true. Forexample, the following statement specifies that the handle count must be greater than 100 and thecompany name must not be Microsoft Corporation:get-process |where {($_.handles -gt 100) `-and -not ($_.company -eq `“Microsoft Corporation”)}PowerShell 101: A Quick Start Guide to PowerShell


26 Lesson 3: How to Use PowerShell's Operations and WildcardsThis statement returns all non-Microsoft processes, as Figure 5 shows.Figure 5: Using the -not operator in an expressionArithmetic OperatorsPowerShell supports the use of arithmetic operators to perform mathematical calculations. Table 4describes the operators and provides basic examples.Table 4: PowerShell Arithmetic OperatorsOperator Description Example Result+ Adds two values 10 + 5 15- Subtracts one valuefrom another- Converts a value to anegative number10 – 5 5-5 + 10 5* Multiples two values 10 * 5 50/ Divides two values 10 / 5 2% Returns the remainderfrom divided numbers10 % 3 1PowerShell 101: A Quick Start Guide to PowerShell


Lesson 3: How to Use PowerShell's Operations and Wildcards 27In addition to using the operators for mathematical calculations, you can use some of the operatorsother ways. For example, you can use the + operator to concatenate string values:“Use + to add two” +“ “ + “strings together.”Figure 6 shows the results of concatenating these two values.Figure 6: Using arithmetic operators toconcatenate stringsThis figure also shows the results for the statement:“abc” * 4In this case, the * operator is used to multiply a string value four times. As a result, four copies of thevalue are returned, and those values are concatenated into one string.My arithmetic-operator examples are very basic. As you work through the lessons, you’ll see morecomplex examples of how these operators can be used. This section is meant only to introduce you tothe arithmetic operators so that you can begin to use them. To learn more about these types of operators,see the about_arithmetic_operators Help file.Moving ForwardIn this lesson, you learned that PowerShell supports a number of operators that let you create expressionsand perform calculations. However, this lesson doesn’t cover all operators. For example, Power-Shell also supports bitwise operators that perform binary operations and assignment operators that assignvalues to variables. I’ll be covering many of these operators as we progress through the lessons. In themeantime, refer to the Power-Shell Help files to learn more about the available operators.PowerShell 101: A Quick Start Guide to PowerShell


28 Lesson 3: How to Use PowerShell's Operations and WildcardsHow to Find Out a Cmdlet’s <strong>Pro</strong>pertiesIn the Where-Object expressions I use in this lesson,I specify several cmdlet properties, such as Lengthand Handles. You can use the Get-Member cmdletto retrieve the members (e.g., properties, methods) ofcmdlets and other objects.Unlike the Get-Command, Get-Content, and Get-Help cmdlets described in Lesson 1, you can’t usethe Get-Member cmdlet in a statement such asGet-Member Get-<strong>Pro</strong>cessTo use Get-Member, you must first specify the objectwhose members you want to retrieve, pass that objectdown the pipeline, then specify Get-Member. Forexample, to view the members available to the Get-<strong>Pro</strong>cess cmdlet, you’d enterGet-<strong>Pro</strong>cess | Get-MemberFigure A shows the members returned by this statement.Notice the Alias<strong>Pro</strong>perty entries under theMemberType column. In addition to regular properties,PowerShell supports alias properties and scriptproperties. An alias property (Alias<strong>Pro</strong>perty) is analternative name for a regular property. For example,the Name alias property refers to the <strong>Pro</strong>cessNameproperty. A script property (Script<strong>Pro</strong>perty) is aproperty whose value is the output of a script. Forexample, the Company property generates a scriptthat retrieves the CompanyName property associatedwith a specific process object.For more information about the Get-Member cmdlet,see PowerShell’s Get-Member Help file. You canfind additional information about all the supportedmember types at technet.microsoft.com/en-us/library/bb978568.aspx.Figure A: Members returned by the Get-Member cmdletPowerShell 101: A Quick Start Guide to PowerShell


Lesson 4: How to <strong>Pro</strong>perly Use Quotes When Working with Strings 29Lesson 4:How to <strong>Pro</strong>perly Use QuotesWhen Working with StringsMost PowerShell statements include string values. Usually, these strings are passed to cmdlets as arguments.In some cases, the strings are enclosed in single quotes. In other cases, they’re enclosed in doublequotes. And sometimes they’re not enclosed in quotes at all. It’s important to understand how to properlyhandle strings. The rules that govern how to do so are often referred to as quoting rules. In this lesson,you’ll learn about these rules. Specifically, you’ll learn when to enclose string values in quotes and whetherto use single or double quotes. In addition, you’ll learn how to flag, or escape, special characters.Working with String ValuesWhenever you enclose text in quotes, PowerShelltreats that text as a string value. So, aslong as the text doesn’t contain any specialcharacters (you’ll learn more about thesecharacters shortly) or reference variables(I’ll discuss how to reference variables instrings in the next lesson), you can enclosethe text in either single or double quotes. Forexample, the following statements achievethe same results:Write-Output “String in quotes.”Write-Output ‘String in quotes.’In these examples, the Write-Outputcmdlet sends a string object down the pipelineor, in this case, directly to the PowerShell console.As you can see in Figure 1, the outputtedvalue is the same for both statements.Figure 1: Enclosing strings in single and double quotesPowerShell 101: A Quick Start Guide to PowerShell


30 Lesson 4: How to <strong>Pro</strong>perly Use Quotes When Working with StringsIn addition to the Write-Output cmdlet, PowerShell’s Out-Host and Write-Host cmdlets output informationto the console. Their differences lie in the details. For example, the Write-Output cmdlet sendsoutput down the pipeline to the next cmdlet. When Write-Output is the last cmdlet in the pipeline, theoutput is displayed in the console. The Out-Host cmdlet sends output directly to the console and offersan optional parameter that lets you view the output one screen at a time, which can be helpful if thereis a lot of output. This is the default output cmdlet, so if you don’t specify an output cmdlet, Out-Hostcmdlet is used. The Write-Host cmdlet also sends output directly to the console. However, Write-Hosthas two optional parameters that let you change the color of the text or text background, thereby creatinga customized console.For basic quoted string values that you want to output directly to the console window, all threecmdlets behave in similar ways. For example, the following four commands all display the string in theconsole window in the same way as in Figure 1:“String in quotes.”Write-Output “String in quotes.”Write-Host “String in quotes.”Out-Host `-InputObject “String in quotes.”Notice that no cmdlet is specified in the first command. As a result, the Out-Host cmdlet is used.For many of the examples in this lesson, I use the Write-Output cmdlet because it outputs an objectin a way similar to many other cmdlets. This lets me demonstrate different principles about quotedvalues. Keep in mind, however, that the Write-Output, Out- Host, and Write-Host cmdlets can behavedifferently in different circumstances. For more information about these cmdlets, see their Help files.If you want to include quotes within a string, you can use single quotes within double quotes ordouble quotes within single quotes:Write-Output “String ‘in’ quotes.”Write-Output ‘String “in” quotes.’If you refer again to Figure 1, you’ll see that inside quotes in both cases are carried to the output.This isn’t the case when you use the same type of quotes throughout the string:Write-Output “String “in” quotes.”Write-Output ‘String ‘in’ quotes.’As Figure 1 shows, the results are quite different. In both cases, the quotes are not displayed anda new line is added. This is because PowerShell interprets the one string as multiple strings and consequentlyadds a line break. For example, PowerShell interprets String as the first string (so it adds a linebreak after that string), then interprets the rest as a different string. You can use double quotes withindouble quotes, but you must escape the inside quotes, which I’ll describe how to do later.Whenever you work with quotes, be careful not to mix up the type of quotes or forget to include one.Otherwise, you might get stuck in a loop that continues to prompt you for an entry, but nothing you entergets you out of the loop. If you run into that situation, press Ctrl+C to return to the command prompt.PowerShell 101: A Quick Start Guide to PowerShell


Lesson 4: How to <strong>Pro</strong>perly Use Quotes When Working with Strings 31Another issue to take into account when defining cmdlet arguments is how Power- Shell treatsnumerical values. As I said earlier, PowerShell treats any values within quotes as strings, even if the valueconsists of all numbers:Write-Output “123”When you execute this statement, the value returned is a string object, as Figure 2 shows.Figure 2: Working with numerical values in stringsYou can verify the value’s type by running the statement:(Write-Output “123”).GetType()This statement uses the GetType method of the object’s type, which in this case is String, or morespecifically System.String, also shown in Figure 2. For more information about System.String and Get-Type, see the sidebar “Getting and Using the System.String Object’s Members.”If you don’t enclose a numerical value in quotes, PowerShell treats the value as a numerical object.For example, the following statement returns an integer object:Write-Output 123PowerShell 101: A Quick Start Guide to PowerShell


32 Lesson 4: How to <strong>Pro</strong>perly Use Quotes When Working with StringsAgain, you can verify the object’s type by using the GetType method:(Write-Output 123).GetType()As you can see in Figure 2, the object’s type is Int32.If a value includes both numbers and letters, PowerShell treats it as a string, whether or not it’s inquotes. For example, the following statement returns a string, as verified by the second statement:Write-Output 123output(Write-Output 123output).GetType()Once again, Figure 2 shows the output of these statements.In most cases, you can omit quotes if your argument is a string with no embedded spaces. Forexample, the following three statements use the Set-Location cmdlet to set the working folder to the Cdrive:Set-Location C:\Set-Location “C:\”Set-Location ‘C:\’Now suppose you want to change the working folder to C:\Documents and Settings:Set-Location `C:\Documents and SettingsThis statement generates an error because it doesn’t know what to do with the tokens (words) afterthe first space. As you can see in Figure 3, the parser interprets “and” as a parameter, and becausethere’s no parameter by this name, the parser generates an error.Figure 3: Handling arguments improperly results in an error messageYou can easily fix this problem by enclosing the entire argument in quotes:Set-Location `“C:\Documents and Settings”PowerShell 101: A Quick Start Guide to PowerShell


Lesson 4: How to <strong>Pro</strong>perly Use Quotes When Working with Strings 33Now when you run this statement, it changes the working folder, as shown in Figure 3.One other important issue when working with strings is how to reference variables within a quotedstring. If you enclose a string in double quotes, the variable’s value is used. If you enclose a string insingle quotes, the literal value is used. As I mentioned earlier, I’ll cover variables and describe how toreference them in strings in the next lesson. However, if you’re anxious to learn more about using variablesin your strings now, refer to the about_quoting_ rules Help file.Escaping Special Characters in StringsUp to this point, the arguments you’ve seen in the examples could have taken single or double quotes.As a result, it would appear that there’s no difference between the two. However, there’s one very importantdifference: Single quotes always treat a string literally, whereas double quotes allow you to escapespecial characters within the text. A special character is one that, when preceded by a backtick (`), takesa specific action that it would not have taken without the backtick. Table 1 lists PowerShell’s specialcharacters.Table 1: PowerShell's Special CharactersSpecial Character`0`a`b`f`n`r`t`vDescriptionInserts a Null valueSends an alert (bell or beep)to the computer’s speakerInserts a backspaceInserts a form feedInserts a new lineInserts a carriage returnInserts a horizontal tabInserts a vertical tab`’ Inserts a single quote`” Inserts a double quoteThe best way to explain this concept is through a few examples. In the following statement, severalcharacters have been escaped in order to change how the text is displayed:Write-Output (“`n`tText includes” + `“`n`t`”escaped`” characters.`n”)PowerShell 101: A Quick Start Guide to PowerShell


34 Lesson 4: How to <strong>Pro</strong>perly Use Quotes When Working with StringsThe first escaped character (the one preceded by the first backtick) is n, which in this context insertsa new line. The next escaped character is t, which inserts a tab. Note that the backtick at the end of thefirst line isn’t being used as an escape character but rather as a continuation character (see Lesson 2). Inthe second line, `n and `t are used several more times. In addition, backticks precede the double quotessurrounding the word escaped. As a result, the double quotes appear in the output. If you refer to Figure4, you’ll see how the new lines, tabs, and double quotes appear. For more information about escapingcharacters, see the about_escape_character Help file.If you try to escape characters in a string enclosed in single quotes, the backtick and special charactershave no effect on the output, other than to be treated literally. For example, the statementWrite-Output ‘`tindented`n`twords’returns the exact string as originally typed, as Figure 4 shows. Note that, in pre-release versions ofPowerShell, you could escape characters inside single-quoted strings, and PowerShell would correctlyparse them. So, you might come across material that says that this is how PowerShell handles singlequotedstrings.Figure 4: Escaping characters in stringsMoving ForwardIn most cases, string values play an important role in creating PowerShell statements. The better youunderstand how to work with strings, the more effective your statements will be. I encourage you tospend time practicing the various ways to use strings. Try enclosing them in single and double quotes,then try running the commands without the quotes. And don’t forget to practice escaping specialcharacters.PowerShell 101: A Quick Start Guide to PowerShell


Lesson 4: How to <strong>Pro</strong>perly Use Quotes When Working with Strings 35Getting and Using the System.String Object's MembersPowerShell treats all strings as System.String objects.This means that you can use the rich set of methodsand properties available to those objects.As shown in Lesson 3, the Get- Member cmdletretrieves an object’s members as the object is passeddown the pipeline. Because a string is passed downas an object, you can use Get- Member for that string.For example, the following statement retrieves theobject members for the string test output:“test output” | Get-MemberAs you can see in Figure A, a string object supportsnumerous methods, including Substring and GetType.If you were to scroll down, you would also find theLength property, which provides the number of charactersin the string.Now suppose you want to learn more about the Substringmethod of the System.String object. You canagain use Get- Member to retrieve the informationyou need. You specify the Substring method as anargument to Get-Member, then pipeline the results tothe Format-List cmdlet:“test output” |Get-Member Substring |Format-ListFigure B shows the statement’s result.Notice that the definition includesdetails about how to use the method.continuedFigure A: Retrieving the members of a System.String objectFigure B: Retrieving details about the Substring methodPowerShell 101: A Quick Start Guide to PowerShell


36 Lesson 4: How to <strong>Pro</strong>perly Use Quotes When Working with StringsGetting and Using the System.String Object's Members continuedThis is the method’s syntax. The syntax specifies thatyou can choose one of two approaches when callingthis method. Those approaches are:System.String Substring(Int32 startIndex)System.String Substring(Int32 startIndex,Int32 length)In the first approach, you provide the target string andan integer that specifies the position in which youwant the substring to start. The method will then returna substring that begins at this position and ends at theend of the string. For example, if the target string is testoutput and you want to return a substring that starts atposition 5, you’d use the statement(“test output”).Substring(5)which would return the substring output. As this statementshows, you must enclose the target string inparentheses, then add a period followed by the methodname and the parameter enclosed in parentheses.In the second approach, you provide the target stringand the substring’s starting position and length. Forexample, suppose you want to return a substring thatstarts at the beginning of the string (position 0) and isfour characters long. You’d use the statement(“test output”).Substring(0,4)which would return the substring test.When you call a method such as Substring or Get-Type, it generates its own object that can be passeddown the pipeline. As a result, you can use Get-Member to retrieve a list of those object’s members.For example, the GetType method returns a System.RuntimeType object, and that object supportsnumerous methods and properties. The followingstatement returns a list of properties available to theSystem.RuntimeType object:(“test output”).GetType() |Get-Member -MemberType <strong>Pro</strong>pertyAs the statement shows, you first enclose the stringin parentheses, add a period followed by the methodname, which in this case is Get- Type. You then pipethe object returned by GetType to Get-Member.Notice that I’ve used the -MemberType parameter todisplay only the returned object’s properties. Figure Cshows the results.Figure C: Retrieving the GetType method's propertiesPowerShell 101: A Quick Start Guide to PowerShell


Lesson 5: How to Access, Create, and Use Variables 37Lesson 5:How to Access, Create,and Use VariablesVariables are virtual suitcases that you can use to store and transport data in your Power- Shell code.Sometimes, the suitcases come prepacked. For instance, PowerShell’s built-in variables and <strong>Windows</strong>environment variables come with data already assigned to them. Other times, you need to pack thesuitcases yourself. Although these userdefined variables take a bit more work to use, they contain exactlywhat you need. But before you can start using built-in, environment, and user-defined variables, youneed to understand the basics.Built-In VariablesPowerShell supports many built-in variables that provide such information as the PowerShell homefolder ($PSHOME) and current working folder ($PWD). To retrieve a list of not only the built-in but alsothe user-defined variables available in the current session, you can run the statementdir variable: | sort nameThis statement starts by using the dir alias to reference the Get-ChildItem cmdlet, which takes variable:as its argument. This argument is referring to the Variable drive, one of several drives supported byPowerShell. As you might have guessed, this drive provides access to built-in and user-defined Power-Shell variables and their values.After the Get-ChildItem cmdlet retrieves the variables and their values, they’re piped to the Sort-Object cmdlet (represented by the sort alias), which sorts the output by the variables’ names. If you don’tsort by name, the variables will be displayed in the order they’re retrieved.Figure 1 shows part of a sorted variable list. Such a list can prove invaluable as long as you’re awareof an important caveat: When you reference built-in and user-defined variables in your PowerShell code,you typically need to precede the variable name with a dollar sign ($). Unfortunately, this list doesn’tinclude the dollar signs in the names.PowerShell 101: A Quick Start Guide to PowerShell


38 Lesson 5: How to Access, Create, and Use VariablesFigure 1: Retrieving a list of built-in and user-defined variablesThe dollar sign makes it easy to distinguish variables from other code elements. For example, thedollar sign lets you easily distinguish between the pwd alias and the $PWD built-in variable. There are afew cases in which you don’t precede the variable name with a dollar sign, which I’ll discuss later.If you want to retrieve the value of just one built-in variable, you can simply enter the variable’sname. For example, if you run$pshomeyou’ll receive the path to the PowerShell home folder.As with any variable in PowerShell, you can use built-in variables in statements. For example, thefollowing statement uses the $PSHOME variable to retrieve a list of the .dll files in the PowerShell homefolder:dir $pshome -filter *.dllPowerShell supports two types of built-in variables: preference (e.g., $MaximumErrorCount) andautomatic (e.g., $PSHOME).You can change the values of preference variables but not automatic variables. If you try to modifyan automatic variable’s value, you’ll receive an error. For a list of preference variables, see the about_preference_ variables Help file. (If this file isn’t available on your system, you can view it at technet.microsoft.com/en-us/library/ bb978529.aspx.) For a list of automatic variables, see the about_automatic_variableHelp file. You can find additional information about built-in variables by viewing theabout_shell_variable Help file.To change the value of a preference variable, you simply use the assignment (=) operator to assigna new value. Take, for example, the preference variable of $MaximumErrorCount, which specifies howPowerShell 101: A Quick Start Guide to PowerShell


Lesson 5: How to Access, Create, and Use Variables 39many errors to save in the error history log for the current session. If you want to change this variable’svalue from the default of 256 to 260, you’d run$maximumerrorcount = 260The new value is used until you reassign a value or end your session.Environment VariablesIn PowerShell, you use the Env drive to access <strong>Windows</strong> environment variables. For example, the followingstatement uses this drive to retrieve the <strong>Windows</strong> environment variables and their values, thenuses the Sort-Object cmdlet to sort the output by the variables’ names:dir env: | sort nameLike the built-in and user-defined variable list, the environment variable list doesn’t show the prefixyou need to include when you reference environment variables in PowerShell code. However, unlikebuilt-in and user-defined variables, which you preface with $, you need to preface an environment variable’sname with $env: when you reference it. For example, the following statement retrieves the windirenvironment variable’s value, which is the path to the <strong>Windows</strong> home folder:$env:windirTo retrieve a list of the .dll files in the <strong>Windows</strong> home folder, you’d rundir $env:windir -filter *.dllYou can change the values of environment variables. For example, suppose you want to change theHOMEPATH environment variable’s value from \Documents and Settings\administrator to \Documentsand Settings\administrator\home. You can use the + operator discussed in Lesson 3 to append the string\home to the HOMEPATH environment variable’s value:$env:homepath =$env:homepath + “\home”The value stays in effect until you reassign a new value or end the session. For more informationabout environment variables, see the about_environment_variables Help file.List-Defined VariablesUnlike some scripting languages, Power- Shell doesn’t require you to explicitly declare a variable beforeyou use it. You simply assign it a value. For example, the following statement assigns the string one twoto the $var1 variable:$var1 = “one two”When you define a variable in this way, you’re actually calling the New-Variable cmdlet and providingtwo arguments to it: the variable’s name and value. For example, the following statement achieves thesame results as the preceding statement:New-Variable var1 “one two”PowerShell 101: A Quick Start Guide to PowerShell


40 Lesson 5: How to Access, Create, and Use VariablesIn this statement, note that the variable’s name isn’t preceded with a dollar sign. When a variable’sname is an argument to the New-Variable cmdlet or to the Set-Variable, Clear-Variable, or Remove-Variable cmdlet (all of which I’ll cover shortly), you don’t include the dollar sign.One advantage of using the New-Variable cmdlet to create a variable is that you can use othercmdlet parameters. For example, you can use the -option parameter to define the variable as read-only:New-Variable var1 “one two” `-option ReadOnlyIn this case, I’ve specified ReadOnly as an argument to the -option parameter. You can also specifyother values as arguments to this parameter. If you specify more than one argument, you need to usecommas to separate them. For a complete list of acceptable arguments, see the New-Variable Help file.When you set a variable as read-only, you can’t change the variable’s value unless you force thechange. However, before I get into the details of how to do that, let’s first take a look at how to updatea variable. Typically, the simplest way to change a variable’s value is to use the = operator to assign thenew value:$var1 = “three”You can achieve the same result by using the Set- Variable cmdlet:Set-Variable var1 “three”Both these statements will reset the value, but only if the variable is not defined as read-only. If it isread-only, you’ll receive an error and you won’t be able to update the value. The way to work aroundthis issue is to use the -force parameter:Set-Variable var1 “three” -forceNow the variable will be assigned the new value. As you saw with the New-Variable cmdlet, theadvantage to using the Set-Variable cmdlet is that you can use additional parameters.Now let’s take a look at how to clear a variable’s value. One approach you can take is to set thevalue to null by using the $null built-in variable:$var1 = $nullOr, you can use the Clear- Variable cmdlet to achieve the same result:Clear-Variable var1However, as before, if the variable is defined as readonly, both these commands will fail. Onceagain, the workaround is to add the -force parameter:Clear-Variable var1 `-forceFinally, if you want to delete a variable altogether, you can use the Remove-Variable cmdlet:Remove-Variable var1PowerShell 101: A Quick Start Guide to PowerShell


Lesson 5: How to Access, Create, and Use Variables 41Not surprisingly, this command will return an error if the variable is read-only. However, theRemove-Variable cmdlet also supports the -force parameter:Remove-Variable var1 -forceIn most cases, you’ll probably find that you can simply use the = operator to create, change,and clear variables. However, if you want to use the New-Variable, Set-Variable, Clear-Variable, andRemove-Variable cmdlets, you can find more information about them in their respective Help files.Different Data TypesNow let’s take a look at some other considerations when using user-defined variables. But first, create$var1 again with the statement$var1 = “one two”because you just used the Remove-Variable cmdlet to delete it. As with built-in variable values,user-defined variable values can be retrieved by entering the variable’s name:$var1Because you assigned a string value to $var1, PowerShell stores the value as a string object. To verifythe object type, you can use the GetType() method:$var1.gettype()Figure 2 shows the results of all three of these statements.Figure 2: Creating a string variablePowerShell 101: A Quick Start Guide to PowerShell


42 Lesson 5: How to Access, Create, and Use VariablesYou’re not limited to string values when you create a variable. You can just as easily assign aninteger:$var1 = 123; $var1.gettype()PowerShell automatically stores the value as the correct type, which is Int32, as Figure 3 shows.Notice that this code includes multiple statements. As I discussed in Lesson 2, you can use a semicolonto manually terminate a statement. So, provided you use semicolons, you can put multiple statementson one line. In this case, I’ve included two statements: the first assigns the numeric value, and thesecond retrieves its type.Figure 3: Assigning different value types to a variableAlso note that this code assigns a value to the same variable used in the previous set of examples. Idid this to demonstrate that the process of creating and updating a variable is the same.Besides strings and integers, you can assign other types of values, such as$var1 = 12.34; $var1.gettype()$var1 = get-date; $var1.gettype()The first line stores the value as type Double, whereas the second line stores the value as type Date-Time, as Figure 3 shows.To append text to an existing string value in a user-defined variable, you can follow the sameapproach I outlined for appending text to an existing string value in an environment variable. Forexample, the following code assigns a string value to $var1, then appends the string four to it:$var1 = “one two three”; $var1$var1 = $var1 + “ four”; $var1PowerShell 101: A Quick Start Guide to PowerShell


Lesson 5: How to Access, Create, and Use Variables 43Figure 4 shows the results.Figure 4: Appending values to a variableNow let’s try a similar operation with numerical values:$var1 = 123; $var1$var1 = $var1 + 4; $var1In this case, PowerShell doesn’t append the number 4, but instead adds 4 to the total amount, asshown in Figure 4. You can, however, define the number as a string by enclosing it in quotes:$var1 = “123”; $var1$var1 = $var1 + 4; $var1The number 4 is now appended to the original value. In fact, you can take this approach with anystring:$var1 = “one two three”; $var1$var1 = $var1 + 4; $var1In this case, the results shown in Figure 4 might seem odd, but PowerShell has done exactly whatyou’ve told it to do.PowerShell 101: A Quick Start Guide to PowerShell


44 Lesson 5: How to Access, Create, and Use VariablesAlthough you can append text or a number to a string value, you can’t append text to a numericvalue. For example, if you attempt to append the string four to the number 123$var1 = 123; $var1$var1 = $var1 + “four”; $var1you’ll receive an error, as seen in Figure 4. You can append values to an existing value only when thetypes are compatible. The important point to remember is that PowerShell tries to do the right thing byletting you assign any type of data to a variable as long as it can be converted to the correct type.Referencing Variables in StringsIn PowerShell, you can use variables in string values. However, the way in which variables are treated atruntime depends on whether you use single or double quotes. When you use single quotes, PowerShelloutputs the variable’s name as entered. When you use double quotes, PowerShell outputs the variable’svalue.For example, let’s assign the value eventlog to a string variable named $svc:$svc = “eventlog”You can now use that variable in your strings. You just type the variable’s name as you would anyother word:Write-Output “The service is $svc.”When PowerShell sees the dollar sign, it interprets the word as a variable because the string isenclosed in double quotes. PowerShell then inserts the variable’s value in place of its name, giving theresult: The service is eventlog.Now let’s use single quotes:Write-Output ‘The service is $svc.’This time, PowerShell treats the variable as a literal value and outputs the variable’s name, giving theresult: The service is $svc.If you want to include both the variable’s name and value in a string, you can use double quotes(but not single quotes) and escape the variable you want to keep as a literal value with a backtick (`):Write-Output `“The value of `$svc is $svc.”(Note that the backtick at the end of the first line isn’t being used as an escape character but rather as acontinuation character.) The result is: The value of $svc is eventlog.If you try to use single quotesWrite-Output `‘The value of `$svc is $svc.’PowerShell outputs the string as it’s entered, backtick and all: The value of `$svc is $svc.PowerShell 101: A Quick Start Guide to PowerShell


Lesson 5: How to Access, Create, and Use Variables 45Using a Variable Alone as an ArgumentIn the preceding examples, you saw how to include a variable in a string value that was passed as anargument to the Write- Output cmdlet. However, in some cases, you might want to use a variable as acmdlet argument without it being part of a string. In that case, you can simply use the variable as theargument. For example, the following command uses the $svc variable as an argument for the name ofthe service: Get-Service $svc If you were to enclose the argument in double quotes, as inGet-Service ‘$svc’you would receive the same result because, as you saw earlier, PowerShell retrieves the variable’s valuewhen it’s enclosed in double quotes. Also as you saw earlier, if the variable appears in single quotes,PowerShell will interpret the variable name literally. As a result, the statementGet-Service ‘$svc’will fail because PowerShell will interpret the service name as ‘$svc’.Moving ForwardVariables play a vital role in effective scripting, whether they’re built-in, environment, or user-defined.You’ll find them a useful tool at the command line and in scripts. Be sure to review the PowerShell Helpfiles for more information on variables, and practice creating and using them. Use the Get-Membercmdlet to retrieve methods and properties and try them out. As you move into more complex code,you’ll find that you’ll be using variables—as well as their methods and properties—in a wide range ofscripting solutions.PowerShell 101: A Quick Start Guide to PowerShell


46 Lesson 5: How to Access, Create, and Use VariablesPowerShell 101: A Quick Start Guide to PowerShell


Lesson 6: How to Work with PoserShell's Built-In Drives and Create New Drives 47Lesson 6:How to Work with PowerShell'sBuilt-In Drives and Create NewDrivesIn <strong>Windows</strong> PowerShell, you access folders and files by providing a pathname, such as C: <strong>Windows</strong>\System32. In this case, the pathname begins with C, which is the drive name. Whenever you access afile-system resource, you must provide the drive name, or the drive must be implicit within the contextof the command, such as when you’re retrieving a list of objects in the current working location.File-system drives aren’t the only type of drives that PowerShell supports. PowerShell supports anumber of drives that provide access to different data stores. For example, as I demonstrated in Lesson 5,you use the Variable drive to access built-in variables and the Env drive to access environment variables.In this last lesson of the PowerShell 101 series, you’ll learn about the available drives and how toimplement them through PowerShell providers that facilitate access to the data stores. You’ll also learnhow to work with PowerShell’s built-in drives and how to create additional drives. By the end of thelesson, you’ll know how to access not only the file system but also the certificate store, the registry, andother data stores.Understanding PowerShell <strong>Pro</strong>vidersAt the heart of data-store access lies the PowerShell providers. A provider is a Microsoft .NET programthat provides a data-access layer between PowerShell and the data. <strong>Pro</strong>viders abstract data access so thatyou can use the same mechanisms within PowerShell to interact with the various stores. For example,you can use the Get-ChildItem cmdlet to access the file system, registry, and certificate store.PowerShell supports a number of built-in providers. To view a list of providers currently available onyour system, you can use the Get-PS<strong>Pro</strong>vider cmdlet in the commandGet-PS<strong>Pro</strong>vider | select NamePowerShell 101: A Quick Start Guide to PowerShell


48 Lesson 6: How to Work with PoserShell's Built-In Drives and Create New DrivesTable 1ists the providers that currently ship with Power- Shell. Because PowerShell is extensible,custom providers can be developed to access other types of data stores. You can then install those providersand access the data stores as you would access the data stores supported by the built-in providers.However, a discussion about custom providers is beyond the scope of this article. See the about_providerHelp file for information.Table 1: PowerShell's Built-In <strong>Pro</strong>vidersTable 1: PowerShell’s Built-In <strong>Pro</strong>viders<strong>Pro</strong>viderAliasCertificateEnvironmentFileSystemFunctionRegistryVariableData StorePowerShell built-in and user-definedaliases<strong>Windows</strong> digital signature certificates<strong>Windows</strong> environment variables<strong>Windows</strong> file system drives, folders, andfilesPowerShell functions<strong>Windows</strong> registryPowerShell variablesDespite the important role that providers play, they are, for the most part, invisible to you withinPowerShell. What are visible, however, are the PowerShell drives you use to access the providers.Working with the Built-In Drives<strong>Pro</strong>viders expose data through one or more PowerShell drives. For example, the File- System providerexposes file-system data through PowerShell drives that have a direct correlation to your <strong>Windows</strong>drives. For instance, the FileSystem provider exposes your <strong>Windows</strong> C drive through the Power- Shell Cdrive.To view a list of PowerShell drives and their associated providers, you can use the Get-PSDrivecmdlet, as shown in the statementGet-PSDrive | sort <strong>Pro</strong>vider, NameThis statement sorts the results first by provider, then by name so that the providers are groupedtogether, as Figure 1 shows. Notice that on my system, the FileSystem provider supports six drives, theRegistry provider supports two drives, and the other providers each support only one drive.PowerShell 101: A Quick Start Guide to PowerShell


Lesson 6: How to Work with PoserShell's Built-In Drives and Create New Drives 49Figure 1: Displaying a list of PowerShell drivesThe preceding statement also displays root information. The root refers to the location within thetarget data store that the PowerShell drive maps to. For example, the HKCU drive maps to the HKEY_CURRENT_USER hive in the registry. For drives that access nonhierarchical data stores, such as Power-Shell aliases and variables, the root value is blank.You can also use Get-PSDrive to retrieve information about a specific drive. For example, the followingstatement retrieves data about the Function drive:Get-PSDrive Function | Format-ListAs Figure 2 shows, this statement returns details such as the name of the provider and a descriptionof the drive.Figure 2: Retrieving drive-specific informationPowerShell 101: A Quick Start Guide to PowerShell


50 Lesson 6: How to Work with PoserShell's Built-In Drives and Create New DrivesNotice that the figure also shows the statementGet-PSDrive -PS<strong>Pro</strong>vider RegistryIn this case, Get-PSDrive returns a list of drives associated with the Registry provider.After you know what drives are available, you can access those drives within your commands. Forexample, you can change your working location to the Env drive with the statementcd Env:\This statement uses the cd alias to reference the Set-Location cmdlet. Figure 3 shows how the commandprompt now reflects the new location.Figure 3: Changing the working locationOnce in that folder, you can run other PowerShell commands, such asdir | where {$_.Name -like “*path*”}In this command, I use the dir alias to reference the Get-ChildItem cmdlet, then filter out all variablenames that don’t contain the string path. The results in Figure 3 show that the Get-ChildItem cmdletworks the same as if this were a file-system drive.You can access any drive type from any other drive type. For example, the following statementretrieves a list of objects in the HKCU drive:dir HKCU:\As you can see in Figure 4, Env is still my working location, but the results are pulled from theHKCU drive.PowerShell 101: A Quick Start Guide to PowerShell


Lesson 6: How to Work with PoserShell's Built-In Drives and Create New Drives 51Figure 4: Retrieving registry information for the current userYou can also change to any drive type from any drive type. For example, the following commandchanges the working location to a registry key:cd HKCU:\Software\Microsoft\Office\As this command shows, not only can you change to a different drive, but you can also change tofolders within that drive, whether it’s in the registry, the file system, or another hierarchical data store. Inthis case, I’ve set the working location to HKEY_CURRENT_ USER\Software\Microsoft\Office.It also doesn’t matter whether you access data through different providers or the same provider. Forexample, the following statement retrieves information from a registry key in a different hive:dir HKLM:\Software\Microsoft\Office\By using PowerShell drives, you can jump from location to location without taking any specialsteps, as shown in Figure 5.Figure 5: Retrieving registry information for the local machinePowerShell 101: A Quick Start Guide to PowerShell


52 Lesson 6: How to Work with PoserShell's Built-In Drives and Create New DrivesTo view specific information about an item such as a registry key, you can use the Get-Item<strong>Pro</strong>pertycmdlet. The following statement retrieves information about the HKEY_LOCAL_MACHINE\SoftwareMicrosoft\ASP.NET key:Get-Item<strong>Pro</strong>perty `HKLM:\Software\Microsoft\ASP.NETAs you can see in Figure 6, the statement retrieves a list of properties and their values. Notice thatthe results also include Power- Shell-specific information, such as the name of the PowerShell drive andprovider.Figure 6: Retrieving registry key propertiesBesides using the PowerShell built-in drives to retrieve data, you can use them to take any actionapplicable to the data store. For example, you can use the New-Item cmdlet to create an object in theregistry:New-Item `HKLM:\Software\Microsoft\TestKey1This command creates theTestKey1 key in HKEY_LOCAL_MACHINE\Software\Micro soft.Figure 7 shows this command’sresults.Figure 7: Creating a registry keyPowerShell 101: A Quick Start Guide to PowerShell


Lesson 6: How to Work with PoserShell's Built-In Drives and Create New Drives 53After you create the key, you can use the New-Item<strong>Pro</strong>perty cmdlet to add a property to the key.(Adding a property in PowerShell is the same as adding an entry in the registry editor.) The followingstatement adds the Test<strong>Pro</strong>perty property to TestKey1:New-Item<strong>Pro</strong>perty `HKLM:\Software\Microsoft\TestKey1 `-Name Test<strong>Pro</strong>perty -<strong>Pro</strong>pertyType string `-Value “test value”The added property has a value of test value, which is a string data type. When you run the statement,PowerShell returns a list of all properties and their values. As Figure 7 shows, the new propertyhas been added.Figure 8: Creating a registry key propertyYou also can take other actions through the PowerShell drives. For example, the following commanduses the Rename-Item cmdlet to rename TestKey1 to TestKey2:Rename-Item `HKLM:\Software\Microsoft\TestKey1 `TestKey2In this command, the first argument identifies the original key and the second argument providesthe new name. You can also use the Remove-Item cmdlet to remove a registry key:Remove-Item `HKLM:\Software\Microsoft\TestKey2As these statements demonstrate, working with a registry drive is similar to working with a filesystemdrive. You can just as easily use the New-Item, Rename-Item, and Remove Item cmdlets with filesand folders—or items in any other drive for that matter.PowerShell 101: A Quick Start Guide to PowerShell


54 Lesson 6: How to Work with PoserShell's Built-In Drives and Create New DrivesCreating PowerShell DrivesUp to this point, I’ve shown you only statements that use the built-in PowerShell drives. However, youcan also create drives based on existing providers. This can be useful when you want to simplify commandsthat you use often.To create a PowerShell drive, you use the New-PSDrive cmdlet. For example, the following statementcreates a drive named ps:New-PSDrive -Name ps `-PS<strong>Pro</strong>vider FileSystem -Root $pshomeThe statement identifies the name of the new drive, then the provider, and finally the root. In thiscase, I use the PSHOME built-in variable to retrieve the PowerShell home folder name. When you runthis statement, PowerShell creates the drive and displays information about the drive, as shown in Figure8. Notice that PowerShell displays the actual root name, not the variable name. (For more informationabout variables, see Lesson 5.)After you’ve created your drive, you can use it just like the built-in drives. For example, the followingstatement changes the working location to the ps drive:cd ps:\As Figure 8 shows, the PowerShell command prompt reflects the name of the new drive. You cannow work in this drive as though you had changed the working location to C:\<strong>Windows</strong>\system32\<strong>Windows</strong> PowerShell\v1.0.To test whether you’re working in the correct folder, you can run the Get-ChildItem cmdlet. Figure 9shows you the type of results you should expect. Notice that the results include the correct name of theworking location. (In this example, PowerShell is running on a <strong>Windows</strong> XP computer. If you run Power-Shell on a different OS, you might see different results because the Power- Shell home directory is set updifferently for different OSs.)Figure 9: Retrieving data through a PowerShell drivePowerShell 101: A Quick Start Guide to PowerShell


Lesson 6: How to Work with PoserShell's Built-In Drives and Create New Drives 55PowerShell also includes the Remove- PSDrive cmdlet, which lets you remove user-defined drives.To use the cmdlet, you must be in a working location other than the one you want to delete. Forexample, the following code changes the working location, then deletes the ps drive:cd C:\; Remove-PSDrive psNote that any drives you create within a session persist only until you end that session, so you don’tneed to remove a drive unless you have a reason to explicitly delete it. For example, you might wantto simplify your list of available drives when you’re no longer using a particular drive. You can persistcustom drives across sessions by modifying your profile file. In a later lesson, you’ll learn how to createand customize profile files. However, if you’re anxious to learn more about profile files now, see theTechNet article “Window PowerShell <strong>Pro</strong>files” (technet.microsoft.com/en-us/library/cc162758.aspx).That's All for NowIn this lesson, I introduced you to Power Shell providers and drives. As the examples demonstrate,you can access a number of data stores in a manner similar to accessing files and folders. In addition,because PowerShell uses providers and drives, the methods used to access data are consistent amongthe data stores. In fact, much of what you’ve learned in the PowerShell 101 series can be applied to thevarious drives.Robert Sheldon is a technical consultant andauthor of material about <strong>Windows</strong>, relationaldatabase management systems, and businessintelligence design and implementation. Hislatest book is Beginning MySQL (Wiley). Findout more at www.rhsheldon.com.PowerShell 101: A Quick Start Guide to PowerShell

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!