PowerShell Tutorials

PowerShell Tutorial for beginners. Windows PowerShell instruction thought-out for those new to PowerShell. In the next few weeks I will be posting a series of PowerShell basics that will provide a good start for a solid foundation. Here is what I have slated:
y y y y y y y

The Windows PowerShell Console - Configuration and Customization. PowerShell Basics - Cmdlets, Parameters, Command Types, Command Information, etc« Output using the PowerShell Format command. Engaging the Windows File System. WMI and .NET primer (real basic) Variables in PowerShell Taking what you have learned and applying it.

The initial lessons are concentrated around PowerShell as a Command Shell. The commands and syntaxes you learn will be utilized in script writing. An enormous feature of PowerShell is the ability to build and test code at the command prompt. If you have experience in VBScript you understand. VBScript doesn¶t have a command line, you write the script, test it, and make adjustments. With PowerShell you can test functionality within the command line before writing it to your script, very powerful!

Windows PowerShell Console
PowerShell Tutorial 1: Configuring the PowerShell Console

PowerShell is required for tutorials on this site. If PowerShell is not installed on the system, please do so before moving on. A page on this site has been provided to assist in installing PowerShell. It can be found at Categories -> PowerShell Downloads > Download PowerShell 1.0. This tutorial is an introduction to PowerShell, PowerShell concepts, and exercises in customizing the PowerShell Console.

PowerShell Intro«
PowerShell is a new« ok how many times have you read that already? PowerShell is a new command shell from Microsoft and yes it is a command prompt and scripting environment, it can even be both at the same time. But what does PowerShell really mean for a systems administrator? What are the benefits in learning PowerShell? If you manage resources with VBScript you already know the answers. Active Directory domains are becoming larger and more complex. For those administrators that are still

chained to GUI tools and the Microsoft Management Console, PowerShell will set you free!!! It has become a daunting task to manage resources in large domains, GUI just won't DUI anymore. For example, take the recent DST (Daylight Savings Time) change. Microsoft was slow to respond (in my opinion) but did supply hot fixes for XP and Windows 2003. Windows 2000 was a different story, system admins had to rely on a manual edit using tzedit.exe (unless you had a premier contract). Am I bringing back any nightmares? Here was my nightmare; the boss asked, "How do we know that the DST hot fixes and the manual tzedit actually worked?" Gulp! Thank god I was already working on the answer to that question. I found a KB Article posted on the Microsoft web site listing the new DST registry entries and their locations. So with VBScript I enumerated the registry settings, based on operating system version, and created a report. I found a 25% failure rate after applying hot fixes and tzedit. So, I wrote another script that would edit the registry settings with the proper configuration. Thankfully, all of my Server Systems (300+) sprung ahead to the proper DST settings. Ok, so now you are thinking "why are we talking about VBScript? This is a PowerShell tutorial!!!" My point is, I know a lot of IT workers that had to manually update the registry when the clocks didn't roll forward, message boards and forums were full of postings. What would you rather do, logon to each server and manually fix the problem or run a script to fix the issue for you? PowerShell would have been a great tool for this situation; I was just more familiar with VBScript at the time. I've read and been asked the following, "VBScript is still a viable tool« so why should I learn PowerShell?" I have a couple of simple answers for that: 1. PowerShell was designed for .NET objects; VBScript does not support a method for communicating or interacting with .NET. We will talk more about .NET in later tutorials. 2. Learning PowerShell will further advance your career. Trust me, it will. This Introduction was not based on what PowerShell is but what PowerShell, as a Shell and a Scripting Language, can do for you. The DST example is only the tip of the iceberg when is comes to the power of scripting languages. What PowerShell "is" you will discover as you continue learning. What's great about PowerShell, you will be able to use it right out of the gate to complete simple tasks. As your knowledge grows you will be able to take on more complex tasks.

PowerShell Concepts
PowerShell is object-based not text-based This concept will take a little time grasp for dos/cmd.exe and batch script writers. Those using VBScript and other programming languages already understand the concept. The basic difference, traditional command prompt output is text-based while output in PowerShell is not. It looks like text but it is actually an object. Why is this powerful? Because the output of a PowerShell command (the object) can be piped into another command without additional programming. With traditional scripting, if you wanted to use the output of one command in another, additional programming would be required to manipulate the data in a format the second command could understand. What is an object? This should sound familiar to the Windows Administrators out there«

"Everything in an Active Directory Domain is an object." Servers, Computers, Printers, Shares, Organizational Units, Security Groups, Group Policy Objects, Users, etc« With PowerShell we can interact with these objects to enumerate information (objectproperties) and/or create, modify, or delete objects and/or object-properties (objectmethods). PowerShell Commands are customizable PowerShell commands are referred to as Cmdlets. With the installation of PowerShell there are over a hundred cmdlets for you to get up close and personal with. The PowerShell team, in their infinite wisdom, created aliases to allow us to use the traditional commands we have become accustomed to (dir, cd, del, copy, etc«). Even the UNIX guys get a break with provided aliases (ls, man, etc«). PowerShell allows you to create your own aliases as well as creating your own cmdlets. Yep, unlike dos/cmd and reskit exe's, PowerShell provides a method to create your own PowerShell cmdlets. PowerShell is a Command line interpreter and a scripting environment In a nutshell you have the best of both worlds within PowerShell. DOS was a command line interpreter, enter command get output. Sure you could use batch files, but in reality a batch file just entered the commands for you. VBScript utilizes WSH (Windows Scripting Host); you can't enter VBScript code in a command prompt. With PowerShell not only can you enter commands, you can build script-blocks from the PowerShell command line. You will be doing this in later tutorials.

Windows PowerShell Console

Let's take a look at the Windows PowerShell Console. Go to Start -> Programs -> Windows PowerShell 1.0 -> Windows PowerShell You can also launch PowerShell from a command prompt or in start -> run by simply typing powershell

You will notice the command prompt PS U:\> PS signifies that you are running PowerShell, U: is the drive letter of my home directory. Yours may be different. Exercise 1: Customize a shortcut to point to a home directory As you have noticed my prompt points to U: Drive. I like to organize my scripts in one location where I can access them quickly. U: is a drive mapping to my home directory on a file server. I've chosen my file server as it is backed up nightly. In this exercise we configure the PowerShell Console to open in a directory called "MyScripts."

1. 2. 3. 4.

Create the following directory - C:\MyScripts. Create a PowerShell shortcut on your desktop. Right-Click on the shortcut and choose Properties. Under the Shortcut tab locate the Start in: text box. Type in the path to the folder created in step 1. C:\MyScripts 5. Click Ok. 6. Launch PowerShell from the desktop shortcut.

PowerShell starts in the directory path we've chosen:

Feel free to choose the directory path of your choice. If your path has a space in it, don't forget to double-quote it. Example: "C:\Program Files\MyScripts." I will be working from the C:\MyScripts directory path throughout the tutorials. Exercise 2: Customizing color and text-size Remember the DOS prompt with the blue background and yellow text? Ok, I'm dating myself but at least I didn't say monochrome. I'm going to change the shortcut to those colors. 1. Right-click on the shortcut and choose Properties. 2. Choose the Colors tab. 3. You will see four radio buttons; Screen text, Screen background, Pop-up text, and Pop-up background. The Screen buttons are self-explanatory; the Pop-up buttons are for colors used in the History Buffer. 4. Set Screen text to yellow, Screen background to blue. 5. Launch PowerShell from the desktop shortcut. PowerShell runs in the colors we've chosen:

Next I'm going to make the text larger so I don't have to squint. 1. 2. 3. 4. Close the PowerShell Console by typing exit. Right-Click the PowerShell shortcut and choose Properties. From the Fonts tab, choose 12 x 16. Click OK. Launch PowerShell from the shortcut.

Do you see the following? I mean can you really see it now?

Who better to learn about PowerShell than from the designer himself! .Jumps to the end of the command line. (In the console type PowerShell tutorial lesson 1) Tab . Customize the shell to your preference. press tab again«). Up Arrow . (In the console type PowerShell tutorial lesson 1) Ctrl+RightArrow .Completes input (in the console type get-c and press tab. Just be aware that when you click "OK" you will be prompted to change the settings of the current window or to modify the shortcut.goes forward one command in the history buffer. y y y y y y y y y y Page Up . F7 .Take a few minutes and play around with all the options in the shortcut's properties. First. watch what happens. Home .goes to the right on word at a time. If you want to go back to the default text-size it is 8 x 12. what the code does is not important): get-acl <enter> get-alias <enter> get-command <enter> get-date <enter> Locate and type the keys below on the keyboard.Shows history buffer (use the up and down arrow keys to navigate the buffer). You can also get to properties by clicking on the PowerShell icon in the upper left-hand corner.Jumps to the beginning of the command line. I'm just going to list them and ask that you play around in the console until you are comfortable with how they work.Jumps to the first command in the history buffer.Jumps to the last command in the history buffer. Ctrl+LeftArrow .Cmdlet The concepts in this tutorial have come from my readings of Bruce Payette's book Windows PowerShell in Action. Bruce is a founding member of the PowerShell team and is a co-designer of the PowerShell language. His book is highly recommended and has been made available from this site. Exercise 3: Editing Features in the PowerShell Console In the last exercise of this tutorial I want to introduce some editing features. Down Arrow . Page Down . Windows PowerShell Cmdlet PowerShell Tutorial 2: PowerShell Commands . enter the following commands at the command prompt (for this exercise.goes to the left one word at a time. End .goes back one command in the history buffer.

and native Windows commands. PowerShell Functions. Unlike most other command-line interfaces.There are four categories of PowerShell commands: Cmdlet (Command-Let). but no need to panic.2 . PowerShell Scripts.naming convention There are over a hundred new PowerShell commands to learn. Each category will be examined in tutorials on this site. This standard simplifies the learning curve and provides a better description of what the cmdlet does. The following command yields all cmdlets that use the verb "Get. Next.1 The "Name" column lists the cmdlets in the "verb-noun" naming convention. let's list all the commands that use a specific verb. Image 2. PowerShell commands have been standardized using a "verb-noun" naming convention know as a cmdlet. so let's get started« cmdlet ." get-command -Verb Get <enter> Image 2. To see a list of cmdlets available in PowerShell type the following cmdlet: get-command <enter> Note: <enter> denotes typing the Enter/Return key on your keyboard. Lesson 2 focuses on the PowerShell cmdlet.

Restart-Service. and remarks. Add. by itself provides the same info as Get-Help *. this will be the most utilized cmdlet until you become more proficient.3 lists eight cmdlets associated with the noun Service: Get-Service. Located in the Categories -> PowerShell Downloads -> PowerShell Graphical Help File."get-service" or "GetService" or even "GeT-SerVIce" is the same command." get-command -Noun Service <enter> Image 2. it is important to find information quickly and easily. I recommend downloading it. Type the following command to see which cmdlets use the noun "Service. New-Service. the PowerShell command line is not case-sensitive. GetHelp cmdlet has been designed for that purpose. The Graphical Help file is great tool for learning and reference.Play around with the -Verb parameter. Start-Service. Get-Help * Information about a specific cmdlet. One thing I want to mention before moving forward. In PowerShell . I'm also going to explain it graphically. try finding commands that use the verbs. Help. O. I find this a tremendous help when attempting to understand new concepts. Getting commands that use specific nouns is just as easy. Help Get-Service. the verb describes an action and the noun describes the "what" to take the action against.k. Get-Help Get-Service Two other forms of the Get-Help cmdlet exist. that sounds kind of graphic« what I mean is I'm going to describe the equivalent action taken when working in GUI tools. Image 2. and Suspend-Service. Set-Service. Get-Service -?. . Getting help In learning new technologies. and Set. Includes description. Get-Help Examples: Information about Get-Help cmdlet. Using cmdlets In this section I will be using Service to demonstrate cmdlets. the noun "Help" and the "-?" parameter. Use Help with a cmdlet as follows. syntax.3 Just as it sounds. Stop-Service. Clear. New. Not only will we be running cmdlets from the PowerShell command line. The Scripting Guys created a graphical Help file which is available on this site. With the help parameter. Get-Help Information about all available help topics.

Launch the Services MMC from Start -> Programs -> Administrative Tools -> Services. As stated earlier. To demonstrate. similar to the list above." This is how we are able to launch services.msc from the PowerShell command-line. Image 2. For this exercise I will be using both the Stop-Service and Start-Service cmdlets. you can launch it by typing services.4 You should now have a list of services on the computer as well as their status.5 Exercise 1: Stopping and Starting a Service.msc from the PowerShell command-line. Which GUI tool gives us the same information? The Services MMC (Microsoft Management Console). one of the PowerShell command categories is "native windows commands. I have chosen the "Computer Browser" service for this example.What services are on the computer? Type the following cmdlet: get-service <enter> Image 2. The . If Administrative Tools are hidden from the Programs Menu.

This is not the complete syntax for the Stop-Service cmdlet." We should see the same change in the Services. This is why I ran the Get-Service command to verify the status changed to "Stopped. If you want to see the full syntax. let's show the status of the Browser Service.current status of the Computer Browser service is "Started" and the "Status Type" is "Automatic. If you choose a service with a status type of disabled. The following syntax stops a service: Stop-Service [-name] or Stop-Service [displayName]. this exercise will not work. To begin. Then Stop it using the Stop-Service cmdlet.6 Note: When you run the Stop-Service cmdlet there is no indication that the service has actually stopped.msc GUI." For this exercise it is important that you choose a service that has a status type of either automatic or manual. In the GUI a Status of "Blank" means "Stopped. Type the following cmdlets: Get-Service -name Browser <enter> Stop-Service -name Browser <enter> Get-Service -name Browser <enter> Image 2." . Lastly check the status. use the Get-Help cmdlet as discussed earlier.

This exercise should give you an indication of the benefits of using PowerShell.7 The following syntax will start a service: Start-Service [-name] or Start-Service [displayName].8 Check the GUI. . Doesn't seem like a big deal until you are asked to stop a service on multiple computers. stop. Get-Service -name Browser <enter> Start-Service -name Browser <enter> Get-Service -name Browser <enter> Image 2. let's check the status. Through PowerShell Scripting you will be able to start. runit. and change status types of a service on multiple computers without much effort. and then kick you feet up on the desk. start the service.Image 2. select the service. Write a script. and verify the status has changed. Look familiar? Again. With just a couple of cmdlets we were able to stop and start a service. Traditionally. an Administrator would launch the GUI. the status of Browser should be "Started" (make sure to refresh the view). and then either stop or start it.

Launch your PowerShell Console and let¶s get started. and a PowerShell alias ³gci´ command. etc« PowerShell Aliases are provided for the purpose of allowing new users the ability to quickly interact with the shell. move.Custom alternative names created by the user. Built-In PowerShell Aliases As previously described. This should be enough to keep you busy for awhile. Use the following cmdlet to get a list of PowerShell Aliases: Get-Alias <enter> Image 3. mv. there are over a hundred cmdlets in PowerShell. man. cat. typing any one of the aliases will result in the running of the ³Get-ChildItem´ cmdlet.1 While browsing through the list. ³dir´ is an alias for ³Get-ChildItem. Unix ³ls´ command. Windows ³dir´ command. cls. Windows PowerShell Aliases PowerShell Tutorial 3: PowerShell Aliases Aliasing in PowerShell allows for the use of commands we become accustomed to. Unix. For example. and an example of using the Service cmdlet.´ This tutorial presents two types of aliases: y y Built-in Aliases . See you in the next tutorial where we will be covering PowerShell Aliases.Predefined alternative names for Windows. As stated before. Windows users can utilize commands like dir. Let¶s test this out. An alias is an alternative name assigned to a cmdlet. built-in aliases are predefined. type the following: dir <enter> ls <enter> gci <enter> Get-ChildItem <enter> . pwd.This tutorial has introduced the PowerShell naming convention. cmdlets. No matter which alias you have chosen to use. and PowerShell cmdlets. User-defined Aliases . getting help. etc« PowerShell also provides a set of aliases for Linux. type. ls. notice that there are multiple Aliases for the ³GetChildItem´ cmdlet.

They exist to assist you while working in the shell. until you become more familiar with the cmdlets. There is really not much more to builtin aliases.2.Image 3. we just ran ³Get-ChildItem´ four times. not much to it. we can verify that each command resulted in the same output.2 Listed in Image 3. Let¶s say I want to create a User-Defined alias for the ³Get-Service´ cmdlet: Set-Alias gs Get-Service <enter> Test your new Alias: gs <enter> . In essence. User-Defined aliases require a little more attention. User-Defined PowerShell Aliases Set-Alias alias command .Simple syntax.

you export the aliases to a text file in which the remote computer could import. function.k. Verify the term and try again. One option is to save the export file to a UNC path so that it is available from a network share. Go ahead and export the ³gs´ alias using the ³Export-Alias´ cmdlet: Export-Alias -Path Aliases. you will receive the following error: ³The term µgs¶ is not recognized as a cmdlet. it would fail. As soon a you quit the session.Recognize the term by creating the alias again: Set-Alias gs Get-Service So. operable program. Say you wrote a script that uses custom aliases. Open ³Aliases.3 That was easy.Image 3. so why does a user-defined alias need a little more attention? Userdefined aliases only last while the PowerShell session is active. your alias is gone forever. Unless. User-defined Aliases using PowerShell Profiles. what do we do? There are two options to explore: y y Import/Export the PowerShell alias. Close your PowerShell session and re-launch PowerShell. Use the ³-Path´ parameter to set the desired location.´ O. .txt <enter> Since I am running from my home directory ³C:\MyScripts´ the Aliases.txt <enter> Do you notice anything odd about the text file? . Import/Export User-Defined PowerShell Aliases The purpose of Importing and Exporting is to make user-defined aliases available to multiple machines. Attempt to use the ³gs´ alias. or script file. we have created a User-defined PowerShell alias and don¶t want to lose it when we quit the session. The remote PowerShell session is not aware of the custom aliases you have created. If you attempted to run your script on another machine.txt´ in notepad: PS C:\MyScripts>notepad Aliases.txt file will be created there.

Import the Aliases.4 Not only did it export the ³gs´ user-defined alias we created.txt <enter> .Export-Alias Image 3. it exported ALL PowerShell aliases.txt file using the ³Import-Alias´ cmdlet: Import-Alias -Path Aliases.txt file. PowerShell will report an error for each alias that already exists. Is this an issue? If we attempt to import the Aliases.

By using the -Name parameter.txt <enter> Image 3.txt <enter> gs <enter> . So with our ³gs´ alias let¶s attempt the following: Export-Alias -Path Alias. There is actually a better way to do this. it will get imported. Let¶s import the Alias. if the alias does not exist. you should get the import error because the ³gs´ alias still exists in the current session.txt file: Import-Alias -Path Alias.5 That looks ugly« but. Exit your PowerShell session and re-launch PowerShell.Image 3.6 That looks much better« What do you think would happen if you attempted to import this file? If your PowerShell Session is still active. you can export only the aliases you choose. The example above was shown to make you aware of a potential problem when you are importing and exporting aliases.txt -Name gs <enter> notepad Alias.

which will be covered in this series.ps1 extension. With Profiles. RemoteSigned .´ This means PowerShell will not run scripts or configuration files. the profile is a script which is denoted by the ³. . You can use any PowerShell editor.We know what this means.All scripts and configuration files must be signed by a trusted publisher. a profile is a script that runs at session startup.PowerShell_profile. Here is a list of policy levels: y y y Restricted . Since the profile is a PowerShell script we will need to edit it. Before editing the file we need to check the PowerShell execution policy.8 In image 3. As already mentioned.txt file and entering the ³gs´ alias provides us with the output expected. User-Defined Aliases using PowerShell Profiles What is a PowerShell Profile? In simplest terms. The location of the Profile is stored in the $Profile variable.Image 3.All scripts and configuration files downloaded from the Internet must be signed by a trusted publisher. We are only going to discuss profiles as it pertains to user-defined aliases. in this tutorial I will be using Notepad. Importing and Exporting allows for the use of user-defined aliases on local and multiple systems.8 you can see the path to my profile. What if you just wanted to use custom aliases on your local system and don¶t want to be burdened with importing a file each time you launch PowerShell? PowerShell profiles allow you to customize the PowerShell environment at launch time. When PowerShell is first installed the default execution policy is ³Restricted. which by default is ³My Documents\WindowsPowerShell\Microsoft. The last section of this tutorial introduces the PowerShell profile. there are many options to customize your PowerShell environment. All PowerShell scripts are identified by this extension. AllSigned .7 No error reported when importing the Alias. which happens to be were ³My Documents´ are stored.ps1 To verify the location of your profile type: $Profile <enter> Image 3.

Step 2. which will delete the current profile. let¶s create a profile by following the steps below: Step 1. Unless you want to create a new profile. how you decide to configure your PowerShell environment. Result should equal ³True. New-Item -Path $Profile -ItemType file -Force <enter> Step 3. test-path $Profile <enter> If the result = False. Edit and Save the profile as shown below: . Verify new profile was created. Create a new profile. If the result = True.ps1 This script file will be called using the $Profile variable each time a PowerShell session is launched. What goes into the script file will be up to you. For now. Verify existence of a profile. Repeat step 1.PowerShell_profile. since the profile is a script file.´ Let¶s open our new profile in notepad: notepad $Profile <enter> Image 3.´ Here is how to set that policy: Set-ExecutionPolicy Unrestricted <enter> Now that the policy is set to run scripts. let¶s have our profile load our custom userdefined PowerShell alias.All scripts and configuration files will run.y Unrestricted . Scripts downloaded from the Internet will prompt for permission before running.9 Isn¶t that great! We have a blank page! The important thing to note: We have a script file called ³Microsoft. No profile exists (continue to step2). Use the ³Get-ExecutionPolicy´ cmdlet to verify policy level: Get-ExecutionPolicy <enter> What is your policy set at? By definition. the execution policy should be set to anything other than ³Restricted. Profile exists (skip steps 2 & 3).´ For this exercise you will set your policy to ³Unrestricted.

and Formatting PowerShell Tutorial 4: Using Cmdlet Options Welcome back! Continuing with your PowerShell Training. Launch a new PowerShell session and verify that your custom alias is functional: gs <enter> Viola! your profile has loaded successfully and your alias is working. Objects. and formatting output. Launch PowerShell and let¶s get started« Common Parameters (options for cmdlets) As mentioned before. . -ErrorAction . Note: not all cmdlets use these parameters. and exit the PowerShell session.a more refined search: Get-Alias -Name gs <enter> PowerShell Parameters. Cmdlets follow a standard ³Verb-Noun´ naming convention and also use common parameters. -confirm . I¶m excited about this tutorial as we begin to define and discover the power of working with objects in PowerShell.Image 3.Instructs cmdlet to perform an action when errors occur. because the PowerShell engine interprets the parameter (not the cmdlet). silently continue. However. close notepad.10 After you have saved the profile.Provides more detail. and how changes are made in the environment. objects.Cmdlet is not actually executed. By the end of this PowerShell training session you should have a good understanding of what an object is. how we gather information. stop. each common parameter is enacted in the same fashion. Use ³Get-Alias´ cmdlet to verify the existence of your new alias: Get-Alias <enter> -or. -Verbose . and inquire.Provides debugging information.Prompt user before executing cmdlet. -debug . Below is a list of the Common Parameters: y y y y y -whatif . the goal of this tutorial is to introduce PowerShell parameters. Such as: continue. the standardization of the PowerShell syntax has reduced the learning curve. provides information about ³what would happen´ if executed.

. Note: not only will you see common parameters but. there is a list of the common parameters the cmdlet supports. Let¶s say you are not sure you want to execute the cmdlet because you are not sure what the ³ExecutionPolicy´ is set to. which provides information on parameters available to the cmdlet. -OutVariable . other parameters that are available as well. Continuing to use the ³Set-ExectutionPolicy´ cmdlet. by continually pressing the ³tab´ key.Hold a certain number of objects before calling the next cmdlet in the pipeline. This is in addition to the standard $error variable. You can verify the ³ExecutionPolicy´ before committing the change: Set-ExecutionPolicy Unrestricted -confirm<enter> Are you sure you want« S<enter> (places the prompt in suspend mode as denoted by ³>>´). In this example. Examples: 1. let¶s use the -whatif parameter to see ³what would happen´ if we used the ³Set-ExecutionPolicy´ cmdlet: Set-ExecutionPolicy Unrestricted -whatif<enter> You are presented with the following: Performing operation ³Set-ExecutionPolicy´ on Target ³Unrestricted´. -OutBuffer . Use the ³Get-Help´ cmdlet for information on parameters available to a cmdlet. Using the same cmdlet.Use a specific variable to hold error information. This is really cool« before you commit any changes you can verify that the cmdlet is going to do what¶s expected. for a cmdlet.Variable used to hold output information. let¶s get-help: Get-Help Set-ExecutionPolicy -Full<enter> In the ³Parameters´ section. type the following at the command prompt: Set-ExecutionPolicy -<tab> You can cycle through available parameters. 2.y y y -ErrorVariable . Would have been great if ³Format C:´ had a -whatif parameter. To view common and other parameters available to the ³Set-ExecutionPolicy´ cmdlet. choose the -confirm parameter to prompt before executing: Set-ExecutionPolicy Unrestricted -confirm<enter> Are you sure you want to perform this action? y y y y y y [Y] Yes (Default is ³Y´) [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help Note: Suspend? This option is very useful. Make sure you are using the dash ³-´ before pressing tab.

Methods are the actions we can perform on the object such as. incandescent. Properties and Methods of the ³Get-Service´ cmdlet. by using PowerShell cmdlets. Do some exploring and experimentation before moving on to the ³Objects´ section. What is an Object? An ³Object´ is something we can gather information from and/or perform an action upon. Example 1. more information exists than what¶s presented (by default) on the command line. In this example. turn on the light bulb and turn off the light bulb. the output of ³Get-Service´ (object) is piped into the ³Get-Member´ cmdlet. An object. in PowerShell. you will use it constantly: ³Get-Member. Introduction to Objects As discussed in an earlier PowerShell tutorial. Since you know how to ³Get-Help´ for a cmdlet.>>Get-ExecutionPolicy<enter> Resricted (or whatever the policy is set to). That information may not be initially visible. and type (florescent. >>exit<enter> (Typing ³exit´ leaves suspend mode and returns to the original command) Are you sure you want« Y<enter> (Confirms ³Yes´ and sets the ExecutionPolicy to ³Unrestricted´).´ This cmdlet is used to examine what properties and methods are available to an object. let¶s look at a ³light bulb.´ The object should be obvious. We¶ve covered a few examples of what you can do with parameters. and script blocks we can interact with an object to provide us with the information we require. Pretty simple right! Let¶s look at an object¶s properties and methods. As an example. it¶s easy to discover which parameters are available to any cmdlet. I don¶t remember where I herd the following explanation but it¶s one that sticks with me. The properties of a light bulb could be color. Ingrain this cmdlet in you head. Since we are working with objects. consists of properties (information we can gather) and methods (actions we can perform). parameters. it¶s a light bulb. PowerShell is object-based not textbased. Get-Service | Get-Member<enter> . wattage. or halogen). Type the following to view the properties and methods of the ³Get-Service´ cmdlet.

´ Don¶t be concerned with this right now.´ .´ My guess is that the value would either be ³True´ or ³False.Get-Member Results Image 4. We have identified which properties and methods are available in the ³Get-Service´ cmdlet. we will be covering ³Types´ in another PowerShell tutorial.1 You should see something similar to Image 4.´ For example. the ³CanStop´ property returns a Boolen ³Type. Just make a mental note that the ³Get-Member´ cmdlet also returns ³data types.1. At this point in your PowerShell training if you are not familiar with what¶s in the definition column. you are looking at ³Data Types.

we are able to make those changes to one or more objects in the environment. I know. -Path parameter points to the root of C:\ drive as the starting point. The boss wants a report of all files that were created in the last day. Why? Because everything in Windows PowerShell is an object. at this point you should recognize that ³user´ is an object. . This means it returns values of this type. Since we connect to objects and gather information (properties). 3. In this example we refine our search to display only properties by using the MemberType parameter. we talk more about operators in a later tutorial. Get-Service | Get-Member -MemberType Method<enter> For a systems administrator. we will discuss ³Types´ in a later PowerShell tutorial.Example 2. The Recurse parameter means we want all subdirectories and files enumerated. Getting Methods of the ³Get-Service´ cmdlet.´ Get-ChildItem -Path C:\ -Recurse | Where-Object {$_. unrealistic right?!? Just follow me on this one. 4. Here¶s an example: Overnight. Getting Properties of the ³Get-Service´ cmdlet.DateTime´ Type.LastWriteTime -gt ³08/25/2007 }<enter> Let¶s dissect what the command is doing: 1. We call the ³Get-ChildItem´ cmdlet because we want to enumerate the file system. I mentioned ³Types´ before as well. Let me go off the page here for a second to explain. which is why we used the ³DateTime´ type ³08/25/2007. Get-Service | Get-Member -MemberType Property<enter> Example 3. objects are the ³Holy Grail´ in managing your environment. Did the method ³Turn light bulb On´ work? I¶m hoping that this discussion on objects is starting to paint the big picture for you. The object returned from the ³Get-ChildItem´ cmdlet is piped into a script block.´ Again. what is ³LastWriteTime´? Type the following command: Get-ChildItem | Get-Member<enter> Do you see a property called ³LastWriteTime´? We told the command to find each object with the ³LastWriteTime´ property that has a value greater than 08/25/2007. 2. the Definition column states that the ³LastWriteTime´ property is a ³System. Your answer« ³No Problem. Can you think of what type of properties and methods are associated with user objects in Active Directory? If the boss asks for a report of all disabled users. someone has placed a large number of files on the file server that has taken up 50% of the remaining free space. Where-Object is a looping statement which finds each object that matches the criteria we are looking for. What I would like you to notice. we are able to compile a report from practically any request our boss throws at us. If the boss requests that a change (method) is made. ³-gt´ is an operator that means greater than.

just separate each property with a comma (. By default. but there seems to be too much white space (spaces) between the columns for my taste.k. LastWriteTime. Use the -Property parameter to list the ³FullName´ property. maybe that wasn¶t what you were looking for either. The boss looks at the list and requests the full path to the files. but now I want the full path to all files and subdirectories. The ³Format-´ cmdlets allow us to choose which format to display results in. the boss wants us to format the report we gave him in the earlier example. To get a list of formatting options. use the <tab> key to cycle through the available parameters for the ³Formattable´ cmdlet. a list. But for now. printers. We are going to get into how we can connect to these objects and enumerate/modify them when we discuss WMI. Reminder: use ³GetMember´ cmdlet to list the available properties: Get-ChildItem C:\Windows | Format-List -Property FullName<enter> If your boss is like mine. and last time a file was modified. How about properties and methods associated with computers. and .) as shown in this example: Get-ChildItem C:\Windows -Recurse | Format-List -Property FullName. Get-ChildItem C:\Windows | Format-Table -AutoSize<enter> O. Expierment with each available parameters to see how format is manipulated. COM objects. there is a parameter -AutoSize to assist us with white space issues. we get the following properties: Name. and LastAccessTime. creation date.LastWriteTime<enter> . type the following command: Get-Command Format-*<enter> Format-Custom Format-List Format-Table Format-Wide Format-Table ³Format-Table´ cmdlet displays data in rows and columns.´ Your answer« ³No Problem!´ To enumerate multiple properties. but doesn¶t always display the best results.NET. similar to what you would see in an Excel spreadsheet. PowerShell attempts to format the view. and a method to either enable or disable it. I usually hear something like« ³that¶s great. Fortunately. Format-List ³Format-List´ cmdlet displays data in« of course.CreationTime. As shown from a previous example. For example: Get-ChildItem C:\Windows | Format-List<enter> By default. Get-ChildItem C:\Windows | Format-Table<enter> I like the table format. Formatting output When we execute a cmdlet we are relying on PowerShell to display results. CreationTime.more than likely it has a property which returns the status of the account. For example let¶s format the output of the ³GetChildItem´ cmdlet for the ³C:\Windows´ directory. and security groups.

You could also sort by ³Name´ or any column you choose. there is a property call ³Company´ for the object returned by the ³Get-Process´ cmdlet. You want to discover which Event IDs are present in the system log: Get-EventLog System | Group-Object eventid<enter> Note: The Name column is the Event ID. By default. Let¶s assign the ³Company´ property to a group: Get-Process | Group-Object Company<enter> The output groups the information as follows: y y y Name . with each property as a header. Format-Wide ³Format-Wide´ cmdlet compresses results of a list. Sort-Object From the example above we are presented with a ³Count´ column. the ³Sort-Object´ cmdlet provides a mechanism to sort results. Count . Just as it sounds. like I did in VBScript. Couple of things to notice here: y y I sorted on the ³Count´ column.Name provided by the Company property of the Get-Process object. even though it¶s not labeled as such. It¶s just fast and I don¶t have to write any code to convert results. Group . As shown above you can pipe results from one cmdlet to another and then another. It¶s not the best html conversion. ³Group-Object´ places the property you specify in the ³Name´ column.The number of process running from each Company. sometimes not. . similar to the old ³dir /D´ command. sometimes the output looks great.Note: You can also use the -Property parameter with the ³Format-Table´ cmdlet to build tables.A truncated list of the processes running. to fit the screen: Get-ChildItem C: | Format-Wide<enter> The results are in list format sorted by column. Let¶s send the results of ³Get-Process´ to html. In this example. etc« Convertto-HTML I love this cmdlet. Here is another example of how to use the ³Group-Object´ cmdlet. This indicates the number of occurrences per each Event ID. You can customize the number of columns using the -Column number parameter: Get-ChildItem C: | Format-Wide -Column 3<enter> Group-Object The ³Group-Object´ cmdlet allows us to format output information based on groups. I¶m going to further build on the command above to sort from most occurrences to least: Get-EventLog System | Group-Object eventid | Sort-Object Count -descending<enter> The results are now sorted from most to least number of occurrences. For example.

doesn¶t always look great« But it is fast and the html code can be edited (to look pretty) if desired. You must have Excel or some other type of spreadsheet installed on the system. Export results to a .csv<enter> 2. 1. Get-Process | ConvertTo-html | out-file ³Processes. the cmdlet preformed the conversion but I want the result saved to an html file.csv<enter> . Invoke-Item Processes. This is equivalent to clicking on a file where the file type determines which application is launched. I¶m going to use the ³Out-File´ cmdlet to redirect the results into a file.html file use the ³Invoke-Item´ cmdlet.html´<enter> To open the . Like I said.html<enter> The default browser is launched presenting the results saved in the html file. In the following examples we are going to Export the processes and open the file in a spreadsheet. Export-CSV This is another formatting cmdlet that you are going to love.csv file´ Get-Process | Export-CSV Processes. It takes results and converts it to a csv file. Open the spreadsheet: Invoke-Item Processes.Get-Process | ConvertTo-html<enter> Well. This is similar to using the redirect symbol ³>´ in the old dos command shell.

we got through PowerShell Parameters. we will continue utilizing these cmdlet options as we work in later PowerShell tutorials. Much more simple that what was required to create the same report in VBScript. We just hit the tip of the iceberg. Objects. Obviously. Alright. .Process CSV Image 4. and Formatting. there are more cmdlet options and parameters we have not covered. PowerShell provides the tools (Get-Help and Get-Member) to explore and learn. so snoop around and get your feet wet. you can use the ³Export-CSV´ cmdlet to quickly document and/or create reports.2 As shown.

. Clears the contents of a file. If you have any comments or questions please use the comment section bellow. LONG DESCRIPTION Windows PowerShell providers are . Sends contents of a file to the output stream. For example. we will be working in depth with objects as we continue our PowerShell training.txt<enter> SHORT DESCRIPTION Windows PowerShell providers provide access to data and components that would not otherwise be easily accessible at the command line. Move a file. Creates a new directory. Cmdlet Alias Cmd Commands Descritption Get-Location Set-Location Copy-Item Remove-Item Move-Item Rename-Item New-Item Clear-Item Set-Item Mkdir Get-Content gl sl cpi ri mi rni ni cli si n/a gc pwd cd. This translates to being able to use the same cmdlets as working with files and folders. This simplifies accessing external data outside the PowerShell environment. The data is presented in a consistent format that resembles a file system drive.NET programs that allow us to work with data stores as if they were mounted drives. Creates a new empty file or folder. Rename a file. chdir copy del move rn n/a n/a n/a md type Current Directory. we can access the registry as if it were a file system. Take a look at the ³about file´ for more information: Get-Content $PSHOME\about_Provider. Set-Content sc n/a Set the contents of a file. which are shown in the table below. Removes a File or directory.NET programs that make the data in a specialized data store available in Windows PowerShell so that you can easily view and manage it. Change current directory. As Objects are the heart of PowerShell and PowerShell scripting. See you in the next PowerShell tutorial« PowerShell Providers PowerShell Tutorial 5: Windows PowerShell Providers PowerShell Providers are . Copy Files.Hope I was able to shed some light on the advantage objects provide over traditional shell ³text string´ output.help. Set the contents of a file.

we obtain a list of available PowerShell Providers: Get-PSProvider<enter> PowerShell Providers Image 5. as we did in VBScript. The providers can also add ³dynamic parameters´ to the built-in cmdlets. What this means is that we no longer have to write code. the exceptions are the . The code is provided for us. to connect to the registry. List Providers available in PowerShell Using the ³Get-PSProvider´ cmdlet. in addition to custom cmdlets that are designed especially for the data. New and Custom Providers can be written. much like a hard drive. simplifying our efforts.dll) built into PowerShell. A library is code that instructs PowerShell to preform an action when we execute a command. Most Providers have only one PSDrive. The PowerShell Software Developers Kit provides documents should you wish to build your own Providers.0 Here is the list of the PoweShell Providers available: y y y y y y y Alias Environment FileSystem Function Registry Variable Certificate PowerShell Drive ³PSDrive´ We connect to PowerShell Providers by mounting the Providers PowerShell Drive(PSDrive). but this goes beyond the scope of this tutorial. These are parameters that are available only when using the cmdlet with the provider data.The data that a provider exposes appears in a drive. You can use any of the built-in cmdlets that the provider supports to manage the data in the provider drive. A Provider is also called a ³snap-in´ which is a dynamic link library (.

2. we want to mount the ³Alias:´ PSDrive. we are now connected to the ³Alias:´ PSDrive. The Alias Provider enables access to all the aliases in PowerShell. PSDrives are only available in the PowerShell environment. Don¶t Forget the colon(:).1 The ³Name´ column reveals the PSDrives available on the system. Now that we are mapped to the Alias: PSDrive we can use the same cmdlets as working with files and folders. Just a quick note.1 shows the PSDrives without the (:) so you have to remember to use it when mounting a PSDrive. View a list of all aliases. The PowerShell Alias Provider We discussed what an Alias ³is´ in PowerShell tutorial 3. Let¶s use this PowerShell training session to explore each of these providers. Get-ChildItem<enter> . Set-Location Alias:<enter> Set Alias Drive Image 5.2 As shown in image 5. Here is how to get a list of the available PowerShell Drives: Get-PSDrive<enter> PS Drives Image 5. Note: The example in image 5. To mount a PSDrive we use the ³Set-Location´ cmdlet. Eample 1.FileSystem Provider(depends on the number of drives on the system) and the Registry Provider(HKLM and HKCU). In this example. You would not able to access the ³Alias:´ drive from a legacy windows command shell. We connect to each Provider using the PSDrive appended with a colon (:).

Get-ChildItem | Get-Member<enter> Properties and Methods Image 5. PowerShell supports the use of wild cards(*) to filter the results. Use the -Name parameter to list all Aliases that start with the letter ³R´.2 Example 2.All Aliases Image 5. Get-ChildItem -Name R*<enter> .3 Example 3. List the properties and methods.

so I¶m going to move along to the next Provider. . Graphically. instead of using a parameter to filter results. you can view the environment variables by going to System Properties -> Advanced Tab -> Click the ³Environment Variables´ button. It provides a listing of all the environment variable defined on the system.4 Example 4. Building on example 3. it is equivalent to running the ³set´ command in a windows CMD command shell. Feel free to use the commands listed in the table (above) and experiment with the Alias Provider. let¶s filter using the ³name´ property of the Alias object. The PowerShell Environment Provider You may already be familiar with what the Environment Providers is.Name Parameter Image 5.5 We have worked a lot with aliases in a previous tutorial. Get-ChildItem | Where-Object {$_.name -like ³R*´}<enter> Where-Object Filter Image 5.

List Environment Variables 1. Get-ChildItem<enter> . Map PSDrive to Environment Provider. Set-Location env:<enter> 3. Get list of available PowerShell Providers.ENV Variables Image 5.6 Example 1. Get-PSDrive<enter> 2. Get listing of Environment Variables.

Create a new variable using the ³New-Item´ cmdlet.´ The Path argument will be a dot (. Get-ChildItem OS<enter> 2.) meaning current location. Obtain the value of an Environment Variable 1.7 Example 2. which would be ³env:´ . Output all properties for the ³OS´ variable. Output the value of the ³OS´ variable. Create a new Environment Variable 1. Get-ChildItem OS | Format-List *<enter> Example 3. Let¶s call the new variable ³MyVariable´ and give it a value of ³This is my new variable.List Variables Image 5.

Connect to the File System Provider. Use ³Get-ChildItem´ to verify the variable has been removed. Listing Files and Directories 1. -Name MyVariable -Value ³This is my new variable´<enter> Create Variable Image 5. the File System Provider is accessed when PowerShell is launched. Get-ChildItem<enter> Example 5. The File System Provider allows you to create.8 Use ³Get-ChildItem´ cmdlet to verify that the new variable exists. and remove files and folders.New-Item -Path . Example 1. Also. Use the backslash (\) character to connect to the root of C: Drive . To remove the ³MyRenVar´ variable we us the ³Remove-Item´ cmdlet. Example 4. Renaming the Environment Variable 1. This section of the PowerShell Providers tutorial explains how to do this. Get-ChildItem<enter> PowerShell File System Provider By default. Now use the ³Get-ChildItem´ cmdlet to verify the change. retrieve. Close and re-launch PowerShell -orconnect to the File System Provider using the ³Set-Location´ cmdlet. the File System Provider allow you to modify files by either appending or overwritting data.´ Rename-Item -Path env:MyVariable -NewName MyRenVar<enter> 2. Removing the Environment Variable 1. Let¶s rename the ³MyVariable´ variable to ³MyRenVar. Remove-Item MyRenVar<enter> 2.

y y First entry is either ³d´ (indicates item is a directory) or ³-´ (indicates item is a file). so that you don¶t have to scroll back to the top. Copy Files. chdir copy Current Directory. ³r´ = read only. Providers allow the use of the same cmdlets. Use ³Ctrl + C´ to stop processing commands in PowerShell. ³Get-ChildItem´ cmdlet or an Alias does not show hidden files and Directories. Mode Image 5. Here is a second look at the cmdlet table. Change current directory. Get-ChildItem<enter> 3. ³h´ = hidden.9 Note: By default. List Files and Directories including sub-direcories. The last 4 entries present the properties of a File and/or Directory (a r h s). List Files and Directories under the root of C: Drive.Set-Location C:\<enter> 2. and ³s´ = system. Cmdlet Alias Cmd Commands Descritption Get-Location Set-Location Copy-Item gl sl cpi pwd cd. ³a´ = archive bit is set. A ³-´ in any of these entries means the bit is not set. the command in step 3 may take awhile. To show hidden files use the ³-force´ parameter. Get-ChildItem -Force<enter> As stated earlier in this PowerShell tutorial. . What is the ³Mode´ column? 5 bits of information you need to know. just like you did in CMD command shell. Get-ChildItem -Recurse<enter> If your file system is large.

Get-ChildItem R*<enter> . Set-Content sc n/a Example 2.txt C:\<enter> Verify file moved.Remove-Item Move-Item Rename-Item New-Item Clear-Item Set-Item Mkdir Get-Content ri mi rni ni cli si n/a gc del move rn n/a n/a n/a md type Removes a File or directory.txt<enter> Verify the file has been renamed. Creates a new directory. Renaming Files and Directories Let¶s rename the NewFile.txt -Type File<enter> Example 4. it will assist you when you leave out required information. Set the contents of a file. For example.txt RenFile. gl<enter> pwd<enter> Example 3.txt to RenFile.txt. New-Item -Path C:\NewFolder<enter> PowerShell will prompt you for the missing parameter« Type: Continuing with the ³New-Item´ cmdlet. Set the contents of a file. Using ³Get-Location´ Cmdlet Use ³Get-Location´ to show current directory. Rename-Item -Path C:\NewFile. New-Item -Path C:\NewFolder -Type Directory<enter> A cool thing about PoweShell. Creating files and Directories Use ³New-Item´ cmdlet to create a New Directory. Get-Location<enter> Using Alias and CMD Command. New-Item -Path C:\NewFolder\NewFile. let¶s say your creating the directory in the example above but you forget the -Type paramter. let¶s create a file in our new directory. Get-ChildItem N*<enter> Example 5. Clears the contents of a file. Move NewFile to the root of ³C:\´ using ³Move-Item´ cmdlet Move-Item -Path C:\NewFolder\NewFile. Move a file. Rename a file. Creates a new empty file or folder. Sends contents of a file to the output stream.

Rename Directroy NewFolder to RenFolder. Rename-Item -Path C:\NewFolder RenFolder<enter> Again, verify the change. Get-ChildItem R*<enter> Example 6. Removing Files and Directories in our last example of this PowerShell training section, let¶s remove the RenFolder and RenFile.txt. Just for fun, let¶s add the -confirm parameter so that PowerShell prompts us to confirm the action. Remove-Item -Path C:\RenFile.txt -Confirm<enter> Press ³Y´ to confirm the deletion of the file and verify the files has been removed. Get-ChildItem R*<enter> You should still see the RenFolder but the RenFile is no longer present. Now remove the directory. Remove-Item -Path C:\RenFolder -Confirm<enter> Again, press ³Y´ to confirm and verify Directory has been removed. Get-ChildItem R*<enter> There are other cmdlets such as ³Clear-Item´ and ³Set-Item´ that enable you to work with data within files. Use ³Get-Help´ on these cmdlets to read about how to use these cmdlets in the PowerShell FileSystem Provider. I personally like to use ³Get-Content´ to output a files contents to the screen and ³Set-Content´ to add information to a file.

PowerShell Function Provider

PowerShell has a set of Functions specified in the PowerShell engine. The PowerShell Function Provider allows us to access these functions using, hope this is starting to sound redundant, the same cmdlets as working with Files and Folders. Not familiar with what a function is? A function allows you to make calls to a block of code. When scripting, if you notice that you are using the same code over and over (within the same script), you should consider creating a function. A function would reduce the amount of code and keep your scripts clean and readable. The examples in the section will help define a Function. Be aware that we are discussing Functions defined in PowerShell, not how to create PowerShell Functions. Creating your own Functions comes later in the PowerShell Scripting tutorials. Example 1. Listing Functions 1. Use ³Set-Location´ cmdlet and connect to the PowerShell Function Provider¶s PSDrive. Set-Location Function:<enter> 2. You should be familiar with what cmdlet comes next« Get-ChildItem<enter>

Functions Provider Image 5.10 Image 5.10 displays the Functions that are defined in PowerShell. ³Name´ is the name given to the function and the ³Definition´ is the code that runs when we call the name. What does it mean to ³call´ a function? In PowerShell, we are only required to type a function name and the corresponding code will execute. For example, typing ³setLocation C:´ navigates to the root of C: drive. We can also navigate to the root of C: just by typing(calling) the ³C:´ function name. PowerShell runs the ³Set-Location C:´ code which places us at the root of C: drive. Let¶s take a look at another example. Example 2. Viewing the Code of a PowerShell Function 1. We are going to use the ³Get-Content´ cmdlet to view the code block of the Clear-Host Function. Get-Content Clear-Host<enter> Output: $spaceType = [System.Management.Automation.Host.BufferCell]; $space = [Sys

tem.Activator]::CreateInstance($spaceType); $space.Character = µ µ; $space .ForegroundColor = $host.ui.rawui.ForegroundColor; $space.BackgroundColor = $host.ui.rawui.BackgroundColor; $rectType = [System.Management.Automatio n.Host.Rectangle]; $rect = [System.Activator]::CreateInstance($rectType); $rect.Top = $rect.Bottom = $rect.Right = $rect.Left = -1; $Host.UI.RawUI.S etBufferContents($rect, $space); $coordType = [System.Management.Automatio n.Host.Coordinates]; $origin = [System.Activator]::CreateInstance($coordTy pe); $Host.UI.RawUI.CursorPosition = $origin; So my guess is that you would be more inclined to calling the ³Clear-Host´ function than actually typing the code required to clear the screen. Can you see how calling a function reduces the amount of code written in the script? Before getting in too deep and making your head swim, I¶m going to end this discussion about this Provider until we talk more about PowerShell Functions and Scripting. For now, let¶s move on to the coolest PowerShell Provider in the world!!!

The PowerShell Registry Provider

If you ever wanted to work with the registry with the same ease as working with the file system, your wish has come true. The Registry Provider allows us to connect to two PSDrives; HKCU (HKEY_CURRENT_USER) and HKLM (HKEY_LOCAL_MACHINE). With the Registry Provider we can:
y y y y y y y

Navigate the registry. Search the registry. Create new registry keys. Delete registry keys. Add new values. Modify existing values. Manage ACLs (Access Control Lists).

Eample 1. Connect to the HKLM PSDrive and List Registry Keys. 1. The two PSDrives we can connect to are HKLM and HKCU. Verify this by checking which PSDrives are available. Get-PSDrive<enter>

Image 5.11

Registry Provider 2. Connect to HKLM PSProvider using the ³Set-Location´ cmdlet. Set-Location HKLM:<enter> 3. We can also connect anywhere in the path. Let¶s connect to the SOFTWARE Key: Set-Location HKLM:\Software<enter> 4. From the Software location let¶s list the keys available. Get-ChildItem<enter> Image 5.12

HKLM We¶re all familiar with the warnings of making changes to the Registry. . Copy Files. chdir copy Current Directory. Just note that you can use the same cmdlets used when working with all PowerShell Providers. I¶m not going to provide examples of making registry changes. Since I wish to only help and do no harm. Cmdlet Alias Cmd Commands Descritption Get-Location Set-Location Copy-Item gl sl cpi pwd cd. Change current directory.

<enter> I used the ³. Here¶s the example: Get-ItemProperty -Path ³HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\HotFix\KB888240 <enter> Now we see all the properties. . Choose any hot fix you wish to enumerate. Set the contents of a file. Sends contents of a file to the Get-Content gc type output stream. -Name Comments<enter> Create and Remove a New Registry Key and Property First. Creates a new empty file or folder. I¶m going to use the ³CD´ alias to navigate to one of the ³Hot Fix´ keys. Let¶s work from the root of SOFTWARE. I will show you one very cool example of using the ³Get-ChildItem´ cmdlet to list installed Hot Fixes on a system: Get-ChildItem -Path ³HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\HotFix´<enter> Note: In the -Path parameter. Move a file. Creates a new directory.Remove-Item Move-Item Rename-Item New-Item Clear-Item Set-Item Mkdir ri mi rni ni cli si n/a del move rn n/a n/a n/a md Removes a File or directory. Set-Content sc n/a Set the contents of a file. Get-ItemProperty . You can also get the properties using the -Path parameter. quoting the path statement was required as there is a space between Windows and NT. how about just a specific property? Get-ItemProperty . Staying with the theme of this PowerShell tutorial.´ as we are currently working within the registry path location. Set-Location -Path HKLM:\SOFTWARE<enter> Create new registry Key and Default Property using ³New-Item´ cmdlet from the table. Rename a file. Clears the contents of a file. New-Item -Name Test -Value ³This is a test string´<enter> Verify ³Test´ key exists Get-ChildItem T*<enter> Verify the default property has the string value we created. CD KB888240<enter> Next question should be« How do we enumerate the information inside the registry key? Simply use the ³Get-ItemProperty´ cmdlet. You should now see a list of ³Hot Fixes´ that have been installed on the system.

enumerate. Example 1.\Test<enter> Next. we will be working with variables when scripting. His task was to create new print queues (with a new naming convention) and cut all the user over to the new print queues. Needless to say. He allowed the script to run for a month or two to ensure that everyone using shared PCs would get the new print queues.. Network Print Queues are stored in the registry as a UNC (\\PrintServer\PrinterName). This example shows just how powerful connecting the registry can be. Let¶s delete the new key using the ³Remove-Item´ cmdlet. The PowerShell Variable Provider What is a variable? I like to think of a variable as a ³little box´ that is used to store information. His boss didn¶t like the naming convention for network printers as they provided no clue of printer type or location. After that time period.Get-ItemProperty -Path .´ I¶m only going to describe what he did in pseudo code as it would take another tutorial to examine his script. What Command to list variables? Get-ChildItem<enter> . He replicated the new script to all Domain Controllers in his environment and edited the company¶s logon script to call the printer script. he would just turn on the print script (uncomment it in the main logon script) and ask the client to re-logon the Domain. and delete registry items just like files and folders. Real-World Example: An associate of mine started working for a banking institution.maybe not! But it is a nice thought). Connect to the PSDrive Variable: and Show a List of Available Variables Connect to the PSDrive. The Variable Provider shows us which PowerShell and user defined variables are available. Get-ChildItem T* Using the Registry Provider we are able to navigate. Created a printer script which used an array to store the old printer names and their new counterparts. his boss thought he was brilliant (which he is) an sent him off to Hawaii (ok . so this is just an introduction. He told the boss« ³No Problem. it looks at the registry keys and if it finds reference to an old print queue name. create. We¶re talking multiple locations around the United States. Another requirement was to automate the process so that clients would not experience down time when printing. it was impossible for a tech to be on-site to remap clients to the new print queues. Remove-Item Test<enter> Verify the key has been removed. it would edit that key with the new value. Set-Location Variable:<enter> Use. The script would change the registry setting from \\PrintServer\OldQueue to \\PrintServer\NewQueue while also preserving the default printer setting. When the printer script runs. He created a second print queue for each printer on all his print servers. Again. if he received calls from clients stating they could not connect to a new printer. Because he was dealing with multiple locations.

You will find yourself using this example more than the others: $MyVar3 = ³This is my third variable. The . the list of variables in example 1. MyVar2. Example 1. just add the ³$´ before the variable name.Name? We can see that $_ must be a variable (all variables are noted by the dollar sign in PowerShell)« and it is. To view the information stored in the PSHome variable. sticking with theme we would do the following: New-Item MyVar -Value ³This is my new variable. there are a lot of entries. we will explore script blocks in a later PowerShell tutorial. $PSHome<enter> The $PSHome variable holds the information of the PowerShell installation path. don¶t show a ³$´ sign.Name}<enter> By now your asking yourself. List the Information in the PSHome Variable In PowerShell. and MyVar3 user-defined variables? Example 4. Example 3.MyVar2. However. Check out the information stored in other variables such as the $Profile and $Home variables. variables hold information.Name is the Name Property of the object. One more PowerShell Provider to go« The PowerShell Certificate Provider Here is the last PowerShell Provider we need to cover. $_ is a special variable the holds the object piped from the ³Get-ChildItem´ cmdlet.´<enter> Let¶s sort the listing of variables by name and verify our newly created variables exist.MyVar3<enter> Let¶s verify the variables have been removed: Get-ChildItem | Sort {$_. Since were talking about File System cmdlets used with providers. variables are preceded by the dollar sign character ($). Remove Variables Let¶s use the ³Remove-Item´ cmdlet to remove the variables we created: Remove-Item MyVar. what is $_. Set Location to the Cert PSDrive and List all the Certificates on the System Set-Location cert:<enter> Get-ChildItem<enter> This command truncates the ³StoreNames´ for good reason. If you want a report of all certificates on a system may I suggest the following: Get-ChildItem -Recurse | Export-CSV ³C:\Certificates.´<enter> You can also use the ³Set-Variable´ cmdlet to accomplish the same: Set-Variable MyVar2 -Value ³This is my second variable. As defined. I know your sick of me saying this but.Example 2.Name}<enter> Do you see MyVar. Get-ChildItem | Sort {$_.csv´<enter> . Create a User Defined Variable There are a few ways to create variables. Using ³Get-PSDrive´ cmdlet we can see that we need to connect to the ³cert´ drive.´<enter> This last example is most commonly used when scripting.

csv´<enter> Certificates Image 5.13 Wow!!! we made it to the end of this PowerShell Training session.View results: Invoke-Item ³C:\Certificates. shortening the learning curve. We only have to learn a few cmdlets. The basic concepts to take away from this tutorial are that PowerShell Providers allow us to use common cmdlets outside of the PowerShell environment. to be affective working with: y y PowerShell Aliases Environment Variables .

Variables.y y y y y Files and directories Functions The Registry Variables in PowerShell Certificates Hope you enjoyed this tutorial. Arrays. . Creating. Operators and Expressions. Arrays. and Hash Tables. Constants. The plan is six new and exciting PowerShell tutorials to explain the fundamentals of the PowerShell scripting language. and Hash Tables What¶s in Tutorial 7: y y y y String manipulation and concatenation. use the comment section for any questions or comments. Printers. Scripting using ADSI Objects (Active Directory Management). explains: y y y Testing conditions and running commands based on results. Processing data with Loops. Here is what will be covered: y y y y y y Variables.´ ³do while´ and ³do until´ loop processing. Scripting using WMI Objects (Computers. Storing and Retrieving information using variables and Constants. Etc«). Modular Scripting Using Functions. Introduce and work with ³if´ and ³Switch´ statements. Conditional Logic Tutorial 8. Constants.Introduction to Script Writing It¶s time to take what we have learned and apply it to writing scripts. Loops Tutorial 9. Using Conditional Logic. Modifying. See you in the next PowerShell Tutorial« Windows PowerShell Scripting Primer PowerShell Tutorial 6: PowerShell Scripting . Using Operators to test conditions. gets loopy: y Applying ³while. and Combining Arrays and Hash Tables.

Navigating and using the WMI namespace. Arrays. Hash Table . Launch PowerShell and let¶s get started« PowerShell Variables Think of a variable as an imaginary box where we store information.y Applying ³for´ and ³foreach´ loop processing. OUs. etc«) Variables. Oh my! WMI: y y y y y y Concept of WMI namespaces. PowerShell enables us to store information using the following methods: y y y Variables . Groups.allows us to store in key-value pairs. and Modify Data In this PowerShell training session we are going to discuss storing. Computers. Two basic uses of variables are: . The WMI Provider. Using the ³Get-WmiObject´ cmdlet. The Active Directory namespace.allows us to store single bits of information. Arrays . Recall. Modular and Dot Source Scripting using Functions Clean up your act in Tutorial 10: y y y Organizing your code Enlisting ³Data Types´ Calling Functions from other scripts PowerShell Scripting using WMI Objects Tutorial 11.allows us to store information in an index. and manipulating data within PowerShell. Querying WMI. Administration without the GUI: y y y y Concepts of Active Directory Objects. retrieving. and Hash Tables PowerShell Tutorial 7: Accumulate. PowerShell Scripting using ADSI Object (Active Directory Objects) Tutorial 12. WMI Classes. Creating and modifying Active Directory Objects (Users. The ADSI Provider.

$Args . type the following: Get-Help about_automatic_variables<enter> In VBScript.y y Store information that will be later utilized within a script. I stated virtually any name as PowerShell does have a set of keywords that are reserved and cannot be used as variable names: y y y y y y y break continue do else elseif filter foreach . Special variables exist. ALL variable names must start with the ³$´ character. used in script blocks. $PsHome . Store information that is a result of running a script.Specifies the user¶s home directory. $Error . and even objects (complete with properties and methods). Note: there are illegal characters such as. variables can contain text strings. $Home . filters.Contains objects for which an error occurred while being processed in a cmdlet. and spaces.Contains an array of the parameters passed to a function. which are pre-defined within PowerShell. The ³=´ operator is used to assign data to a variable. and the where statement. it¶s automatically declared. PowerShell will throw an error if you use an illegal character. we have to declare variables before using them. . integers. In PowerShell. names are not case sensitive. Once data is assigned to a PowerShell variable. Special Variable Examples y y y y y $_ . For example: dim strComputer dim strUser dim intDate strComputer = ³MyComputer´ etc« In PowerShell.The directory where the Windows PowerShell is installed. Here is a simple example of creating a variable in PowerShell: $strComputer = ³Computer1 <enter> There is a ³Set-Variable´ cmdlet that can also be used: Set-Variable -Name strUser -Value ³John Doe´<enter> You can use virtually any variable name you choose. To view the complete list of Special Variables in PowerShell. ! @ # % & .Contains the current pipeline object. We have worked with one of these variables ($_) in a prior tutorial.

Go ahead and verify the data value for the ³strUser´ variable. Just be conscious of this rule when using the ³Set-Variable´ cmdlet. you do not use the ³$´ character when defining variables. you can use any naming convention you wish. Working with Strings A [sting] is a ³text string´ data type.´ Again. I continue to use the caMel case naming convention I became accustomed to in VBScript. it might look like something this ³$intMegaBytes.0 The output verifies the data in the $strComputer variable is the ³Computer1 text string. Write-Output $strComputer<enter> -or just type$strComputer<enter> $strComputer Variable image 7. Let¶s verify that the $strComputer variable is holding the data we assigned to it. If I were working with numbers. There are many data types that we will be working with in PowerShell: Type Description [int] [long] [string] [char] 32-bit signed integer 64-bit signed integer Fixed-length string of Unicode characters A Unicode 16-bit character . The first part of the name (str) reminds me that the variable I¶m working with contains ³text string´ data.y y y y y y y y function if in return switch until where while When naming variables. $strUser<enter> Did you get John Doe for the output? Yes« great! No?« I knew you were going to skip the long version of using the ³Set-Variable´ cmdlet. Most of the time I use ($strComputer = ³computerName´) to create variables. Note: If you use the ³Set-Variable´ cmdlet and specify the -Name parameter.

[byte] An 8-bit unsigned character [bool] Boolean True/False value [decimal] An 128-bit decimal value [single] Single-precision 32-bit floating point number [double] Double-precision 64-bit floating point number [xml] Xml object [array] An array of values [hashtable] Hashtable object Yep. As stated at the beginning of this PowerShell training session. variables are stored for later use. PowerShell substitutes the value of variable $strA.Tom drives a fast car. Here is an example: $strA = ³Hello ³<enter> $strB = ³World!´<enter> $strC = $strA += $strB<enter> $strC<enter> We used += to join together variables $strA and $strB and store the new ³text string´ in variable $strC. we will be discussing them all at some point« String Concatenation Concatenation is the process of joining together two strings. Aside from joining strings we can also replace words using the -replace parameter. Like so. the output of the ³Write-Host´ cmdlet is . $strC = $strA + $StrB.Tom drives a $strA car. Let me give you an example of what this means: $strA = ³fast´<enter> Write-Host ³Tom drives a $strA car. either double-quotes(´ ³) or singlequotes(¶ µ). $strA = ³Go east young man!´<enter> $strB = $strA -replace ³east´. Working with Numbers . Both result in the same output.¶<enter> Output . This is interpolation. Let¶s see what happens when using single-quotes: $strA = ³fast´<enter> Write-Host µTom drives a $strA car.´<enter> By double-quoting. Interpolation occurs when a string variable is enclosed in double-quotes and does not occur when single-quoted. PowerShell does not substitute the variable. The output from $strC is Hello World! Most of the time you will see two strings joined together by using just the ³+´ operator. ³west´<enter> $strB<enter> Go west young man! What the heck is Interpolation? Quotes are used when working with string data. What¶s the difference? Glad you asked« It¶s called Interpolation.

/ or /= Division.9). it knows that $x = 1 is an integer data type. enough math class.k.9<enter> PowerShell Operators y y y y y y = Assigns a value to a variable. Note: PowerShell has two additional operators that you will use frequently. Though it is not required. * or *= Multiplication. $x = 10 * 2 / 5 * 2 + 5 * 5<enter> $x<enter> What answer did you get? Hopefully 33. Here are some examples: [string]$strComputer = ³MyFileServer01 <enter> [int]$x = 9<enter> [decimal]$y = 9.or -= Subtraction. Assigning integer and decimal values are simple: $x = 1<enter> $y = 1. it is considered good form to assign the data type of a variable. y y ³++´ Increments a value by 1. it is minus minus or (. For example. multiplication and division are preformed then addition and subtraction. Equations are read from left-to-right. Refer to the data type table presented earlier in the tutorial. ³±´ Decrements a value by 1. It also knows that $x = ³Hello World!´ is a string data type. Make a mental note of these operators as you will be using them often in your script writing. O. The PowerShell engine can automatically recognize the data type assigned to a variable.-) without the space. Examples: .PowerShell works with a number of data types. causing havoc with your script.2<enter> $x<enter> $y<enter> There are those rare occasions when PowerShell may have not assigned the proper data type to a variable. + or += Addition. -Hard to see. % or %= Modulus (retrieves the remainder of a division operation). for example integers(9) and decimals (9. . PowerShell follows the rules of math. What about: $x = 10 * 2 / 5 * (2 + 5) * 5<enter> $x<enter> Parenthesis can be used to alter the order of the mathematical rule.

add 5 and 9. 9. The first item in an array is assigned the value . Create a variable named $x and assign the number 7.strA += strB $x = 9<enter> $y = 5<enter> $x . Using two variables.14 strA + strB -or. Answers provided below the exercise: 1.´ 6. 3.$y<enter> $y + $x<enter> $x = 1<enter> $x++<enter> $x<enter> $x = 5 * 2 / 10 + 7 / 3 * 2<enter> $x = 6 PowerShell Arrays Variables can also store arrays which by definition are an indexed list of values. Answers: 1. Here are nine exercises to complete. Concatenate the following variables. 5. 3. Assign the number 1 to variable $x and increment by 1. Create a variable named $Pi. $strComputer = ³FSrv01 $x = 7 [int]$y = 11 [decimal]$Pi = 3. 5 * 2 / 10 + 7 / 3 * 2. Each item is assigned a unique index number. Create a variable named $strComputer and assign the files server name FSrv01. 6. assign the data type and number 3. subtract 5 from 9. 7. 2. Create a variable named $y. strA = ³This is a ´ and strB = ³text string. 4. 9.14 5. Using two variables. 7. 8. See if you can get through them all without looking at the answers. 4. assign the data type and number 11. 2. Get the answer for the following equation. 8.$x = 1<enter> $x<enter> 1 $x++<enter> $x<enter> 2 $x++<enter> $x<enter> 3 $x±<enter> $x<enter> 2 We will work with more data types when the advanced PowerShell tutorials are launched.

to paste in PowerShell just do a right mouse click. 4. 8. The answer is by using an array! To create an array.´ variable.ps1 (PowerShell) script file to run. and so on. $strComputers[2] = ³Server4 <enter> Verify the element was modified: $strComputers<enter> Using the + operator. 9. array index numbers start at 0.of (0). This changes the item Server3 to Server4. we can combine arrays: $x = @(1. ³Server2 . If you¶ve looked at the PowerShell scripts in the Microsoft Script Center Repository. You could run the script on a remote computer by modifying the code like this strComputer = ³RemoteComputerName´. Just copy and paste the code into the PowerShell Console. 10)<enter> $z = $x + $y<enter> $z<enter> Back to our discussion on using arrays to get information from multiple computers. List values by their index number: $strComputers[0]<enter> $strComputers[1]<enter> $strComputers[2]<enter> We can also modify elements in an array.´ means the local computer the script is running on. Here is a typical script taken from the Microsoft Script Repository that enumerates the BIOS information on the (strComputer = ³. Let¶s take the discussion above and use an array to connect to multiple remote computers: $strComputers = @(´Server1 . ³.´) local computer. I¶m quoting. the next item (1). notice that a lot of scripts only run on the local computer by using strComputer = ³. How to list the values in the array: $strComputers<enter> List the number of items within the array using the count property. we create a variable and assign the array. what if you want to run the script against multiple computers on your network? Ok« besides using a logon script! In essence a logon script still runs locally and you have limited control over when it runs. then (2). $strComputers. Also each array value is separated by a comma. 5)<enter> $y = @(6. we can list an item by it¶s index number. Arrays are noted by the ³@´ symbol. 2. Note: you don¶t have to copy the following script code into a . One of the more popular uses of an array is to run a script against remote computers. But. . Remember. Here I¶m modifying an element in an existing array by providing the index number and the new string value. 7. 3. ³Server3 )<enter> We now have three values stored in the $strComputers variable. Note: Since I am working with string values.Count<enter> Now that we know there are three elements within the array.

SoftwareElementID write-host ³Software Element State: ´ $objItem. ³computer2 .Manufacturer write-host ³Name: ´ $objItem.´ $colItems = get-wmiobject -class Win32_BIOS -namespace root\CIMV2 -comp $strComputer foreach ($objItem in $colItems) { write-host ³BIOS Characteristics: ´ $objItem. $strComputer = @(´computer1 .SMBIOSMinorVersion write-host ³SMBIOS Present: ´ $objItem.ListOfLanguages write-host ³Manufacturer: ´ $objItem.OtherTargetOS write-host ³Primary BIOS: ´ $objItem. FYI .BiosCharacteristics write-host ³BIOS Version: ´ $objItem.SMBIOSBIOSVersion write-host ³SMBIOS Major Version: ´ $objItem.ReleaseDate write-host ³Serial Number: ´ $objItem. Copy and paste your new code into PowerShell.Caption write-host ³Code Set: ´ $objItem.SMBIOSMajorVersion write-host ³SMBIOS Minor Version: ´ $objItem.CodeSet write-host ³Current Language: ´ $objItem.LanguageEdition write-host ³List Of Languages: ´ $objItem.BuildNumber write-host ³Caption: ´ $objItem.When the code has been copied into the shell.SerialNumber write-host ³SMBIOS BIOS Version: ´ $objItem. Just another cool thing you can do with PowerShell« $strComputer = ³. just hit <enter> twice to get the results. Create an array with two (or more) computers. This time you choose which ones.SoftwareElementState write-host ³Status: ´ $objItem.BuildNumber .PrimaryBIOS write-host ³Release Date: ´ $objItem.InstallDate write-host ³Language Edition: ´ $objItem.InstallableLanguages write-host ³Installation Date: ´ $objItem.Status write-host ³Target Operating System: ´ $objItem.BIOSVersion write-host ³Build Number: ´ $objItem.Version write-host } Now we want the same information from multiple remote computers. ³computer3 ) $colItems = get-wmiobject -class Win32_BIOS -namespace root\CIMV2 -comp $strComputer foreach ($objItem in $colItems) { write-host ³BIOS Characteristics: ´ $objItem.BIOSVersion write-host ³Build Number: ´ $objItem.IdentificationCode write-host ³Installable Languages: ´ $objItem.CurrentLanguage write-host ³Description: ´ $objItem.TargetOperatingSystem write-host ³Version: ´ $objItem.BiosCharacteristics write-host ³BIOS Version: ´ $objItem. Use notepad and change the computer names in the array.SMBIOSPresent write-host ³Software Element ID: ´ $objItem.Name write-host ³Other Target Operating System: ´ $objItem.you must have local admin rights on each computer to run the script.Description write-host ³Identification Code: ´ $objItem.

write-host ³Caption: ´ $objItem. Hash Tables A Hash table is also known as a dictionary.Name write-host ³Other Target Operating System: ´ $objItem.Caption write-host ³Code Set: ´ $objItem.SMBIOSMajorVersion write-host ³SMBIOS Minor Version: ´ $objItem.SMBIOSMinorVersion write-host ³SMBIOS Present: ´ $objItem.IdentificationCode write-host ³Installable Languages: ´ $objItem.Version write-host } For more information on building arrays to enumerate remote computers.SoftwareElementID write-host ³Software Element State: ´ $objItem.TargetOperatingSystem write-host ³Version: ´ $objItem.SMBIOSBIOSVersion write-host ³SMBIOS Major Version: ´ $objItem.InstallableLanguages write-host ³Installation Date: ´ $objItem.Manufacturer write-host ³Name: ´ $objItem.ReleaseDate write-host ³Serial Number: ´ $objItem. The ³key´ and ³value´ entries can be any data type and length. The elements must be quoted if they contain a space.SerialNumber write-host ³SMBIOS BIOS Version: ´ $objItem.InstallDate write-host ³Language Edition: ´ $objItem. Just like an array we designate a hash table with the @ symbol.SMBIOSPresent write-host ³Software Element ID: ´ $objItem. There are differences.SoftwareElementState write-host ³Status: ´ $objItem. It is an array that allows you to store data in a ³key-value´ pair association.LanguageEdition write-host ³List Of Languages: ´ $objItem. Creating a hash of users associated with their employee number: $EmpNumbers = @{´John Doe´ = 112233. Hash elements are separated by the semi-colon. ³Dave Davis´ = 223344. here is a very cool article I¶ve written: 3 easy steps to get information from remote computers.PrimaryBIOS write-host ³Release Date: ´ $objItem. ³Justine Smith´ = 334455}<enter> Verify the hash table was created: $EmpNumbers<enter> .CurrentLanguage write-host ³Description: ´ $objItem.Status write-host ³Target Operating System: ´ $objItem.CodeSet write-host ³Current Language: ´ $objItem.ListOfLanguages write-host ³Manufacturer: ´ $objItem. array elements are enclosed in parenthesis () where hash ³key-value´ pairs are enclosed in curly brackets {}.OtherTargetOS write-host ³Primary BIOS: ´ $objItem.Description write-host ³Identification Code: ´ $objItem.

A process or application may stop running. For example. See you in the next tutorial.Remove(´Rose Jones´)<enter> Verify record deletion: $EmpNumbers<enter> To Remove all records in the hash table. Hash tables are associative arrays that use a ³key-value´ pairs. Thanks again for your time« In our next PowerShell training session we are going to talk about using Conditional logic.1 Looks like a mini-database. we use the clear method: $EmpNumbers. Conditional Logic allows us to write scripts in a complex environment. How would we find John Doe¶s employee number? $EmpNumbers["John Doe"]<enter> Add a new employee record: $EmpNumbers["Rose Jones"] = 445566<enter> Verify the creation of new ³key-value´ pair. Arrays consist of numerous values that can be stored in a variable. Launch PowerShell and let's get started« Comparing Data . it is much easier to find values within the array (as there is an association created). a script might prompt for user input and run a block of code based on the data supplied by the user.Hast Table Image 7. Since a hash table is like a dictionary. it adds the intelligence required to create decision-making scripts. triggering an action within a script. This makes it difficult to find values. As with other programming languages. $EmpNumbers<enter> Delete an employee record: $EmpNumbers. Standard arrays are indexed starting from the number 0.Clear()<enter> To recap. variables are items of information that we store for later retrieval. Script code can be executed based on conditions that exist or occur. PowerShell is a dynamic scripting language. unless you¶re a large brain and can tell me what value was assigned to index 245.

The result is "True" Tom -ieq TOM. you can force PowerShell to compare values based on case-sensitivity. you're telling PowerShell to be "case-insensitive. By appending an "i" to the operator. "TOM" and "tom" would compare "equal to" (-eq)." Examples: Tom -eq TOM. they exists within PowerShell and must be used. The result is "False" Table 2: PowerShell Logical Operators: Operator Description -not Not ! Not -and And -or Or Now that we have the table listings of Operators. let's do some examples to show their use and results. Table 1: PowerShell Comparison Operators: Operator Description -eq -lt -gt -ge -le -ne Equal to Less than Greater than Greater than or Eqaul to Less than or equal to Not equal to I'm not going to join in the great debate over why these operators where chosen. 7 -eq 7<enter> Result is "True" 7 -ne 7<enter> Result is "False" 7 -lt 10<enter> Result is "True" 7 -gt 10<enter> Result is "False" "Tom" -eq "tOm"<enter> Result is "True" . However. Special note: When comparing text strings. by default PowerShell is not case-sensitive." Appending a "c" forces PowerShell to compare as "case-sensitive. The result is "True" Tom -ceq TOM.We are going to compare data using the following PowerShell Comparison and Logical Operators.

Using the "if" Statement The if statement syntax: if (condition) {code block} elseif (condition) {code block} else (condition) {code block} y y y y condition = an expression that results to a Boolean Value (True or False). my name is Troy as the condition ($x -eq 2) resulted in a True value and executed the script block {}. my name is Mary"} else {"I have no idea what my name is?"} The result should be Hello. elseif (optional) = test an alternative condition if preceding condition was False. then either executes or sidesteps code blocks based on the result. $x = 2 #creates a variable x and assigns 2 as the value if ($x -eq 5) {Write-Host "Hello my name is Bob"} elseif ($x -eq 4) {Write-Host "Hello. The results are used in the decision-making process within PowerShell scripts. if . once an if statement . either True or False. what do we do with them? We need a way to apply comparison results with conditional logic (the decision-making process).\clogic.ps1<enter>" -or.Does the same as the if statement with the exception that it can evaluate multiple comparisons. This is the same as a "select case" or "case" statements in VBScript and other programming languages. if statements require result of the comparison to be True to execute it's associated code block.evaluates a comparison.type ". switch . each having the ability to execute code blocks. code block = what to execute if condition is True."Tom" -ceq "tOm"<enter> Result is "False" I'm going to skip the logical operators for now.ps1 file and save it to the "MyScripts" directory. But I purposely threw you a curve ball. PowerShell supports two logic statements to help out: 1. What's important to understand is each code snippet is providing a result. we'll get back to them in a moment.ps1 if you are currently working in the MyScripts directory. else (optional) = executes it's code block whenever none of the if or elseif statements return a True result. 2. Notice that the last elseif statement ($x -gt 1) would also result in a True condition. Let's do a simple script that shows the if statement in action. so why doesn't it's script block get executed? This is by design. Copy the code into clogic. Conditional Logic Now that we have results. my name is Troy"} elseif ($x -gt 1) {Write-Host "Hello. Run the script: "C:\MyScripts\clogic. my name is Sue"} elseif ($x -eq 2) {Write-Host "Hello.

2195") { write-host "Computer Name: " $strComputer write-host "OS Version: Windows 2000 Server" $colPrinters = Get-WmiObject -Class win32_PrintJob -namespace "root\CIMV2" ` -computername $strComputer foreach ($objPrinter in $colPrinters) { write-host "Name: " $objPrinter. Windows 2003."} write-host "±END OF REPORT±" .1. PowerShell would run the code block associated for each OS.Version -eq "5.ps1 and execute the script. Real-World Example: Sometimes different Operating Systems use different WMI classes and/or properties. The way around this is to use a switch statement which we will discuss in this PowerShell training session. Here's the code I used: Copy the following code into a .Name write-host "Description: " $objPrinter.0.Description write-host } } # if OS not identified else {write-host "The OS for: $strComputer is not supported.Description write-host } } # if statement to run code for Windows 2000 Server elseif ($OS.condition results in a True value the associated script block is executed and PowerShell stops testing subsequent conditions.3790")) { write-host "Computer Name: " $strComputer #nested if statement if ($OS.Version -eq "5.Name write-host "Description: " $objPrinter.2.Version -eq "5.Enter Computer Name" $OS = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" ` -ComputerName $strComputer # if statement to run code for Windows XP and Windows 2003 Server.ps1 script file. I used an if statement to test the OS version and based on the version.2.1.3790") {write-host "OS Version: Windows 2003"} $colPrinters = Get-WmiObject -Class win32_Printer -namespace "root\CIMV2" ` -computerName $strComputer foreach ($objPrinter in $colPrinters) { write-host "Name: " $objPrinter.Version -eq "5. Name it PrintReport. and Windows 2000. if (($OS.Version -eq "5. I ran into this difference when attempting to enumerate printers on Windows XP.2600") -or ($OS.2600") {write-host "OS Version: Windows XP"} elseif ($OS. $strComputer = Read-Host "Printer Report .

The -and operator means that all conditions must be True to execute the script block. it's associated script block will execute.When the script is executed. Pretty cool stuff going on here.2600") {write-host "OS Version: Windows XP"} elseif ($OS.results in a False value and skips the script block. if (!(1 -eq 1) .2. For example: if (1 -eq 1) .Name .3790") {write-host "OS Version: Windows 2003"} $colPrinters = Get-WmiObject -Class win32_Printer -namespace "root\CIMV2" ` -computerName $strComputer foreach ($objPrinter in $colPrinters) { write-host "Name: " $objPrinter.Enter Computer Name" Creates a variable called $strComputer and assigns a value supplied from user input.3790")) Here is where we talk about Logical Operators.results in a True value and runs the script block. Step 4. Example: if ((1 -ge 1) -and (2 -ge 1)) . let's break it down. Step 2. $strComputer = Read-Host "Printer Report . Used for keeping scripts legible should you run out of space. PowerShell reads the line as: $OS = Get-WmiObject -Class win32_OperationSystem -namespace "root\CIMV2" Computername $strComputer Step 3. The -or operator means at least one of the conditions must be True to execute the script block. you are prompted to enter the computer name you wish to enumerate. whereas the second is False. you're now able to enumerate other computers on your network.One of the conditions are True so.Both conditions are True.2. The Not operators -not and ! (both mean NOT) allow you to modify the results of a condition. For example: if ((1 -gt 2) -or (2 -gt 1)) . if (($OS. Even though it looks like two lines of code. Step 1. Operator Description -not Not ! Not -and And -or Or What you need to know.The first condition is True. it's actually one line of code.2600") -or ($OS. By adding the "Read-Host" cmdlet.Version -eq "5. The "`" escape character means to continue as one line.Version -eq "5.Version -eq "5.1.1. Something else to look at. $OS = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" ` -ComputerName $strComputer Creates the variable "$OS" and assigns the win32_OperatingSystem class object. { write-host "Computer Name: " $strComputer #nested if statement if ($OS. script block executes.Version -eq "5. if ((1 -ge 1) -and (2 -le 1)) . The script block is skipped.

can be. Step 6. If the result in step 5."} Outputs " The OS is not supported. else {write-host "The OS for: "$strComputer" is not supported. Once the block completes. Now you are stating to see how complex PowerShell. If none of the conditions are True in step 3. PowerShell continues reading the script and finds the "else" statement. { write-host "Computer Name: " $strComputer write-host "OS Version: Windows 2000 Server" $colPrinters = Get-WmiObject -Class win32_PrintJob -namespace "root\CIMV2" ` -computername $strComputer foreach ($objPrinter in $colPrinters) { write-host "Name: " $objPrinter. in this example that would be« Step 5. PowerShell skips to Step 8. in RED. elseif ($OS. we can nest additional if statements within code blocks. PowerShell moves to the next if statement. and writes "±END OF REPORT±" to let the end user know it has completed.0. and writes "±END OF REPORT±" to let the end user know it has completed. if one of the conditions are True the script block in step 4. the script block in step 6. is False. PowerShell skips to Step 8. . The script block then enumerates the win32_Printer class and sends the requested property information to the screen.write-host "Description: " $objPrinter. Step 7.Description write-host } } In step 3.2195") If this condition results in a True value. is executed. runs when all conditions in the script end with a False value.Note.Description write-host } } The result of the script block outputs the following information to the screen: y y y y Computer Name OS version Requested Property information of the win32_PrintJob class. as a scripting language. Once the block completes.Version -eq "5. is executed." Step 7. The script block writes the following information to the screen: y y y y The Computer Name The OS Type .Name write-host "Description: " $objPrinter.

Modify the script to prompt user for "Computer Name:" . The PowerShell switch statement organizes a collection of tests that are evaluated using the same expression.name + " is a: " switch ($objWMI. Value = A value. The Switch statement syntax: switch (expression) { (test) {code block} value {code block} default {code block} } y y y Test = An evaluated expression. there may come a time when too many additional tests lend to difficult script writing and down-right ugliness. the script block output the role using the "Write-Host" cmdlet. There are other times where you want to test multiple conditions that result in multiple True values and you don't want the script to stop testing when it receives the first True value (as it does with an if statement). write-host "±END OF REPORT±" Let's you know the script has completed. Using the Switch Statement for Multiple Comparisons Since we can use elseif statements to test multiple conditions.domainRole) { 0 {Write-Host "Stand alone workstation"} 1 {Write-Host "Member workstation"} 2 {Write-Host "Stand alone server"} 3 {Write-Host "Member server"} 4 {Write-Host "Back-up domain controller"} 5 {Write-Host "Primary domain controller"} default {Write-Host "The role can not be determined"} } In this example I used a number value which correlates to the value of the domainrole property within the win32_ComputerSystem WMI class. like a number or text string. Here is an example from Ed Wilson's PowerShell book: "Windows PowerShell Step by Step. based on conditions that exist in our environment. Default = Default code block to run if none of the expressions return a True value. And how we can write if statements to test those conditions and run script blocks according to the results of those tests.ps1 and run the script: $objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2" "Computer "+ $objWMI. The option that allows you to accomplish this is the switch statement. This example shows just how dynamic our scripts can be.Step 8. When the value was returned as True." Save the script code as ComputerRoles.

Unlike if statements. as long we have local admin rights. See you in the next PowerShell tutorial« Conditional Logic Using Loops PowerShell Tutorial 9: Getting Loopy The last PowerShell training session introduced Conditional Logic.domainRole) { 0 {Write-Host "Stand alone workstation"} 1 {Write-Host "Member workstation"} 2 {Write-Host "Stand alone server"} 3 {Write-Host "Member server"} 4 {Write-Host "Back-up domain controller"} 5 {Write-Host "Primary domain controller"} default {Write-Host "The role can not be determined"} } Now that we can input the $strComputer value. We successfully demonstrated how we can control the flow of a script base on conditional responses.1) {Write-Host "Congratulations. This next example has no real purpose other than demonstrating how the switch statement works using the (test) expression with multiple True value results.$strComputer = Read-Host "Enter Computer Name" $objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2" ` -computername $strComputer Write-Host "Computer: $strComputer is a:" switch ($objWMI. The results should be obvious. we can run this script on any remote computer in the environment.11) {Write-Host "This script block better not run"} } Conditional logic is the foundation for dynamic PowerShell script writing. which takes flow control to the next level. In the next PowerShell training session we are going to build on what we have learned and introduce Loops. you found the difference correctly"} (1 . controlling execution of script blocks with if and switch statements. Here are the loops we will be working with in this tutorial: . Looping is a basic programming process that allows us to repeat a command and process large amounts of data. test expressions that correctly equal 10 will run: switch (10) { (1 + 9) {Write-Host "Congratulations. Without this ability. Copy and Paste the code into the PowerShell shell. you applied addition correctly"} (1 + 10) {Write-Host "This script block better not run"} (11 . switch statements continue running when True value matches are found. writing scripts would be tedious if not next to impossible. So it is possible that more than one code block will be executed.

$i++} while ($i -le 5) . Example: do while . the loop continues to run. while . $i = 1 do {Write-Host $i. foreach .Script block executes until the condition value = True.Same as ³do while. 3. using the comparison operator -le (less than or equal to).Code block writes the output of the variable.or written like this $i = 1 do { Write-Host $i $i++ } while ($i -le 5) Output: 1 2 3 4 5 What the code is doing: 1. while . do .Count to 5 Type the code into notepad and save with the .Script block executes as long as condition value = True. Syntaxes: do while do {code block} while (condition) while while (condition) {code block} Both loops run code block while the condition is True. do while runs the code block (at least once) before testing the condition.The condition statement compares the value of $i to the number 5. the difference between the two. As long as the condition is true. This is one of those rules you will want to remember when troubleshooting scripts. If you remember. even if the condition = False. 2. while tests the condition before executing the code block. you can always count on the do while loop to execute the code block at least once.ps1 file extension or copy and paste into PowerShell. $i++ increments the value of the variable by 1 each time the code block is executed (looped).Script block executes a specified number of times. do while and while do while and while Loops executes ³while´ the condition value stays True. So if required. Creates the variable $i and assigns the Integer value of ³1 . . for .´ do until .Executes script block for each item in a collection or array.y y y y y do while .

so kind of a simple ³poorman¶s´ example of creating a monitoring system. it¶s provided to help you . It can actually be any application in your environment. Basically. The following is reported to the console window: ³The Application Notepad failed to respond on: 10/25/2007 14:16:07 Run the script again if you wish to restart the application. Step 2. Step 4. Run the NoteMon.ps1 #launches Notepad Notepad #Setup a do while loop that does nothing while property value is True. Solution: We¶re going to use PowerShell to build a simple script to monitor the process and report when a failure occurs. OK. Exit or Close Notepad. We have been asked to monitor the application and report any failure and log the time the failure occurred. it just depends on how long your command statements become. Close all current running versions of Notepad (if applicable). Again. The <carriage return> or <enter> delimits code when using multiple lines. the semi-colon (. do {} While (get-process notepad | select -Property Responding) #Code to run when loop stops (when notepad is closed) $strTime = get-date Write-Host ³The Application Notepad failed to respond on: $strTime´ Step 3. $i++} .) is a delimiter which allows us to separate commands when writing code on a single line. As already stated. Let¶s look at the same example using the while loop. We¶re going to use a do while loop to watch the ³Responding´ property of the ³Get-Process´ object cmdlet. Write the script. Get-Process | Get-Member<enter> Step 1. Either way is correct. save as NoteMon. From an earlier PowerShell training session I showed you how to get an object¶s properties and methods using the ³Get-Member´ cmdlet.or written like this $i = 1 while ($i -le 5) { Write-Host $i $i++ } In the code examples I¶m showing both ways of writing script blocks. either single line or multi-line. $i = 1 while ($i -le 5) {Write-Host $i. Move notepad so that you can see the PowerShell console.This simple example is just to help you with understanding the concepts. Real-World PowerShell example: Scenario: Our company is having application issues with Notepad and it is mission critical (LOL). we will be using the ³Responding´ property for our script.ps1 script.

Here is the example. Syntax: do {code block} until (condition) Example: $i = 1 do {Write-Host $i. ³No Experience Required. Since 6 is greater than 5 the condition value becomes True. rather than just counting numbers.´ You can read my review and pick up a copy from this site. halting the loop from executing further.txt do until The do until loop is the opposite of do while.understand the looping concept and to give you a better real world example. $strResponse = ³Quit´ do {$strResponse = Read-Host ³Are you sure you want to quit application? (Y/N)´} until ($strResponse -eq ³Y´) . It executes the code block until the condition is True. Additional Reading: Get-Content $PSHome\about_while.help. It¶s a fun book that I recommend for beginners. in other words it runs while the condition value is False. Real-World PowerShell Example: Jerry Lee Ford¶s book (Microsoft Windows PowerShell Programming for the absolute beginner) teaches PowerShell through game creation. $i++} until ($i -gt 5) Output: 1 2 3 4 5 In this example the script block runs until the variable ($i) is incremented to the value of 6. Jerry uses the do until loop to control the collection of user input.

for The standard use of the for statement it to run the code block a specified number of times. repeat) {code block} Note: each of the three parameters are optional. separated by commas. separated by commas. I copied the code into PowerShell and typed in numerous responses. .).one or more commands. then the condition is tested again. Don¶t confuse this with separating commnads within a parameter using commas. therefore the script block was execute again and prompted the user for input.one or more commands.) to delimit the parameters.Resolves to a Boolean True or False value. This variable is the basis for the condition to be tested in the next portion of the for statement. Each time the response did not equal ³Y´ the value of the condition was False. Example: for ($i=1. $i -le 5.do until loop Image 9. condition. that run each time the loop repeats. Commonly used to modify a variable that is tested inside the ³condition´ portion of the for statement. Condition . If you omit a parameter you are required to still use (. that run before the loop begins. Here is the example showing variable assignment outside the condition and how it would look. y y y initialization . Syntax: for (initialization. Repeat . PowerShell evaluates the condition each time the loop runs. We assigned the variable ($i=1) within the condition statement. Commonly used to create and initialize a variable with a starting value. $i++) {Write-Host $i} Output: 1 2 3 4 5 Couple of things to take note: y y We delimit each parameter with a semi-colon (. Since parameters are optional we could have assigned the variable outside of condition statement. If the condition is True the code block is executed. example in BLUE.0 Looking at the image.

be careful.txt foreach The foreach loop description from the PowerShell Help file: The foreach statement (also known as a foreach loop) is a language construct for stepping through (iterating) a series of values in a collection of items. $i -le 5. $i=1 for ($i -le 5.1.Length (length would be 5 entries in the array) so 5 .don¶t panic. for ($i=1 $i -le 5 $i++) {write-host $i} The for loop can also be used to process elements within an array. 4.help. 4=5). $int.$i=1 for (. If we set the variable to 1. your in an infinite loop!!! Just type ³Ctrl + C´ to quit PowerShell execution. $i++) {Write-Host $i} Test what would happen if you omit a parameter forget to delimit (. $ints = @( 1. 3. 1=2. $i -le $ints. 2=3. 2. Forgetting to delimit an omitted parameter can cause some unexpected results. maybe a later release? Additional Reading: Get-Content $PSHome\about_for.) and attempt to run the code.Length . run script block as long as $i is less than or equal to 4. The condition statement states. Output: 1 2 3 4 5 You should not have any issues working with arrays.1 = 4. I dealt with this in VBScript and was hoping it would have changed with PowerShell. If your code becomes large you can always delimit using <carriage return>. $i++) {Write-Host $i} OK . 5) for ($i=0. our output would have been 2 3 4 5 <blank>. . When the Write-Host cmdlet runs it gives us the following entries (0=1. as long as you remember that indexing begins with 0 (zero). 3=4. $i++) {Write-Host $ints[$i]} Do you know why the example sets the variable ($i) to 0 (zero) rather than 1? Remember from the ³Arrays´ tutorial that arrays are indexed starting with the number 0.

CurrentClockSpeed write-host ³Device ID: ´ $objItem.Name write-host } Listing disk information $strComputer = ³. 2. I have presented many examples of foreach loops on this site.The simplest and most typical type of collection to traverse is an array. It doesn¶t required testing a condition and it doesn¶t care how many elements exist in the array. Note: Those writing VBScript code will have to get use to not using ³Next´ as PowerShell doesn¶t require the keyword to move to the next item in the collection.´ $colItems = get-wmiobject -class ³Win32_DiskDrive´ -namespace ³root\CIMV2 ` -computername $strComputer . $strComputer = ³.L2CacheSpeed write-host ³Name: ´ $objItem.L2CacheSize write-host ³L2 Cache Speed: ´ $objItem.CpuStatus write-host ³Current Clock Speed: ´ $objItem. foreach loop is the most typical statement used when working will arrays and collections. Real-World Examples: How about listing processor information. let¶s see how the foreach loop works $ints = @(1. Syntax: foreach ($<item> in $<collection>) {code block} Sticking with our number example. The foreach loop runs the script block against each element within the array. However. Most of the Microsoft PowerShell Scripts in the Scripting Center use this loop. notice that we are not testing a condition. 3. You point it and it runs.´ $colItems = get-wmiobject -class ³Win32_Processor´ -namespace ³root\CIMV2 ` -computername $strComputer foreach ($objItem in $colItems) { write-host ³Caption: ´ $objItem.DeviceID write-host ³L2 Cache Size: ´ $objItem. Within a foreach loop it¶s common to run one or more commands against each item in an array. As stated in the help file.Caption write-host ³CPU Status: ´ $objItem. 5) foreach ($i in $ints) {Write-Host $i} Output: 1 2 3 4 5 Looks a little like the for loop example presented earlier. 4.

Perfectly legal and a concept that we will discuss as you progress through these PowerShell Training sessions. break and continue.{{}} . A break statement appearing in a code block of a foreach. Additional Reading: Get-Content $PSHome\about_foreach. Notice the code block . the break statement causes the loop to exit.Responding -eq ³True´){Write-Host $Item. $i -le 10.txt Varying Loop Processing There are two statements. The following example shows how to use a break statement to exit a for statement: for($i=1.DeviceID write-host ³Interface Type: ´ $objItem.foreach ($objItem in $colItems) { write-host ³Description: ´ $objItem.Model write-host ³Partitions: ´ $objItem. that allow you to alter the execution of a loop when certain conditions are met. foreach ($item in Get-Process) {if ($item.Description write-host ³Device ID: ´ $objItem.Status write-host } Let¶s say we want to determine which processes are running on our computer. the Windows PowerShell reaches the break statement the first time through the for loop.what I¶ve done is called nesting. the break statement causes a code block inside of a switch statement to exit and thus the entire switch statement exits.Name}} Just showing that we can add the conditional logic if statement within the foreach loop to give us more control over the data we wish to retrieve. the break statement exits the for loop when $i equals 1.Partitions write-host ³Size: ´ $objItem.MediaType write-host ³Model: ´ $objItem. In the case of the switch statement. . The Break Statement Excerpt: Taken from the PowerShell help file.InterfaceType write-host ³Media Type: ´ $objItem. In the case of the looping statements. or do loop or in a switch statement. $i++) { Write-Host $i break } In this case. ends the code block.Size write-host ³Status: ´ $objItem. while. for. Even though the for statement evaluates to true until $i is greater than 10.help.

at which point the break statement runs and the foreach loop exits.40) foreach ($var in $varB) { $i++ if ($var -eq 30) { break } } Write-Host ³30 was found in array position $i´ In this example. Consider the following foreach statement example: $i=0 $varB = (10. The third time through the loop. $i equals 3 and the $val variable equals 30. If the arguments of the for statement test a value that is modified by the for statement. The if statement inside evaluates to false the first two times through the loop. program flow returns to the top of the while loop if $ctr is equal to 5. In up-coming PowerShell Let¶s start off be defining the terms: .It¶s more common to see the break statement used inside of a loop where there is some inner condition to be met. the $i variable is incremented by 1. Each time through the code block. The result is that all numbers between 1 and 10 except 5 are displayed. an infinite loop can result. In this PowerShell Training session you learned how to control script block flow using loop processing. Additional Reading: Get-Content $PSHome\about_break. the foreach statement iterates the $varB array.txt The Continue Statement Excerpt from PowerShell help file: In a script. You were also able to process large amounts of data by looping through a collection and enumerating properties of an object. while ($ctr -lt 10) { $ctr += 1 if ($ctr -eq 5){continue} Write-Host $ctr } Note that in a for loop.30. the continue statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements: y for y foreach y while EXAMPLE In this example.help.20. execution continues at the first line in the loop.

y y Function . $y) { $Ans = $x + $y . Method 1: Passing Arguments in a comma separated list. named the function ³Time. Not to mention it improves readability and makes complex PowerShell scripts manageable. We will also briefly talk about filters. Filter . Function Time {Get-Date}<enter> Call the function by typing the FunctionName Time at the command prompt. Passing Arguments to Functions There are multiple ways to pass arguments to a function. It is intended as an introduction.´ omitted the optional parameters. Function Add ($x. Function Syntax: Function(keyword) FunctionName (parameters) {script block} The syntax uses the keyword Function.A function allows you to name a block of code. and assigned the Get-Date cmdlet within the script block. This PowerShell training session introduces the concepts of a Function and a Filter. a FunctionName you provide. Notice that the parameters enclosed in parenthesis and separated by a comma. Example 1. optional parameters. It allows me the ability to call script blocks multiple times within a script. Create a Function called ³Time´ which runs the Get-Date cmdlet when called. I¶ll introduce some common methods. Now let¶s start adding some parameters. this tutorial will teach the concept of functions used for modular scripting and how to build libraries of reusable code. much like an array.1 Simple stuff right! We defined a function using the ³Function´ keyword. PowerShell Functions The main reason I use functions is script organization. advance techniques will be covered in the PowerShell advanced tutorials launched early next year. and the script block.A Filter (as it sounds) takes large amounts of pipeline data and displays only the results of interest to you. cutting down on the amount of code writing to accomplish my task. PowerShell Function image 10. The code block can then be called (by its name) once or multiple times anywhere from within your script. With that being said.

notice that we are defining the arguments within the scriptblock {}. and Hash Tables .The Answer is 12 image 10. Function Add { param ($x.2 Method 2: Using the Param keyword.Write-Host ³The Answer is $Ans´ } Result Copy the code into PowerShell and hit enter twice to get back to the command prompt. $y) $Ans = $x + $y Write-Host ³The Answer is $Ans´ } Type .Add 10 12<enter> Addition image 10. The Param keyword must be the first word inside the script block. at the command prompt type the function and arguments for $x and $y variables: Add 10 2<enter> You should see the following result . Arrays. . When using the Param keyword.There is a special variable $Args which contains an array of the parameters passed to a function. Now.3 Method 3: If you recall from PowerShell Tutorial 7: Variables. Let¶s use this variable to show how we can pass an argument using string expantion.

Function HAL {´What are you doing $args ?´}<enter> Type in the FunctionName and an Argument: HAL Dave $Args image 10.5 Defining Data Types Remember the ³Data Type´ table that was introduced in PowerShell training session 7? Type Description [int] [long] [string] [char] [byte] [bool] [decimal] [single] [double] [xml] [array] [hashtable] 32-bit signed integer 64-bit signed integer Fixed-length string of Unicode characters A Unicode 16-bit character An 8-bit unsigned character Boolean True/False value An 128-bit decimal value Single-precision 32-bit floating point number Double-precision 64-bit floating point number Xml object An array of values Hashtable object .4 You can use multiple $Args variables to pass more than one parameter. Example 2. Function Add { $args[0] + $args[1] }<enter> Type: Add 5 8 Multiple $Args image 10.

Although. Function Add { Param ([int]$x = 0.´ } Data Type Error image 10.The argument A is not an integer and cannot be automatically converted as we defined the variable requirement as an integer ([int]$x). Best practices would recommend that you always define the Data Type for a variable as it prevents parsing errors. Therefore PowerShell gives us the error in image 10.6. y Assigning a Default Value We can also assign a default value should an argument not get passed to the function. Age A .The argument 10 is an integer and is accepted by PowerShell resulting in the output You are 10 years old. there may be instances were it is required to define (or hard code) the expected data type for a variable. The expected result is an integer. [int]$y = 0) $Ans = $x + $y Write-Host $Ans } . otherwise the script would fail. Let¶s test this: Function Age { Param ([int]$x) Write-Host ³You are $x years old.PowerShell does a good job of automatically setting data types for us. For example.6. you have written a script that asks the users age.6 Notice to two commands I ran in image 10. y Age 10 .

we attempted to send an alpha character when the expected entry for the variable is an integer resulting in a conversion error. I wanted to make a point that sending the wrong data type does not result in the variable being assigned the default of 0.7 So I created the Add function with the default variable of $x=0 and $y=0. Add . Add A . What happens when I run the following commands: y y Add 10 2 . The result is 12.Name -eq ³Windows´} } Next Type the following command which pipes the cmdlet output to the function we defined: Get-ChildItem -Path C:\ | FindFolder<enter> . y Using the PowerShell Special Variable ³$input´ The $input variable allows a function to access data coming from the pipeline. First build the function to find the Windows Folder: Function FindFolder { $input | Where-Object {$_. the default was used for $x and $y resulting in 0 + 0 = 0.Data Type Error image 10. For example let¶s say were looking for the folder ³Windows´ and we don¶t know where it is located.Again.Variable $x becomes 10 and $y becomes 2.Since we did not send any arguments.

In this example we run the Get-ChildItem cmdlet telling it to start at the root of C:\ drive. if we ran this command by itself we would get all the files and directories just under the root of C: drive. In this example we will use a filter to find the Hosts file on a system. By piping the information to our function.$input Results image 10.Core\FileSystem::C:\Windows\system32\drivers\etc I know that there are other ways to filter this information in PowerShell. The examples provided were to show how this task can be accomplished using functions.PowerShell.8 So. the information is stored in the $input variable and only the folder named ³Windows´ is allow to pass. PowerShell Filters A Filter and a Function are essentially the same.Name -eq ³hosts´} } Next. Filter Syntax: Filter(Keyword) FilterName (parameters) {Script Block} . we use the -recurse parameter to search all directories and subdirectories under the root. Let me show you how we can use a function to find a needle in the haystack. But what results is it filtering? By itself it is just a function that does nothing until we send piped results to the $input variable. since were not sure if the directory containing the hosts file is a directory under of the root of C: drive. Next let¶s talk about filters. what are we doing here? We created a function call FindFolder which uses the ³Where-Object´ cmdlet to filter results based on the Name property. Simple enough. Create the Function: Function FindHosts { $input | Where-Object {$_. Use the following command: Get-ChildItem -Path C:\ -Recurse | FindHosts<enter> Eventually we find the hosts file and the location Directory: Microsoft. The difference is how they process data.

We will be working more with filters as we progress. Here is where the Function and Filter differ.´ $colItems = get-wmiobject -class ³Win32_Processor´ -namespace ³root\CIMV2 ` -computername $strComputer foreach ($objItem in $colItems) { write-host ³Caption: ´ $objItem.L2CacheSpeed write-host ³Name: ´ $objItem. From the ³Microsoft Scripting Center´ you find these two scripts. most of the feedback I have gotten points to Dot Sourcing as being the most commonly used method. just take in the concepts. A function uses the $input variable to contain pipeline information whereas the filter uses a special variable $_ that contains the current pipeline object. For now.DeviceID write-host ³L2 Cache Size: ´ $objItem.The syntax is the same as defining a Function except the ³Filter´ keyword is used.L2CacheSize write-host ³L2 Cache Speed: ´ $objItem. Real World Examples Organizing Your Code There are two methods I use to organize code: 1.CpuStatus write-host ³Current Clock Speed: ´ $objItem.Caption write-host ³CPU Status: ´ $objItem. Say you want to inventory your system.´ $colItems = get-wmiobject -class ³Win32_DiskDrive´ -namespace ³root\CIMV2 ` -computername $strComputer .Name write-host } List Physical Disk Properties: $strComputer = ³. filters are widely used and more efficient when large amounts of data are passed through the object pipeline. gathering information about the Processor(s) and Disk(s) available on the system.CurrentClockSpeed write-host ³Device ID: ´ $objItem. Modular Scripting Example I¶m going to take two PowerShell script examples from the ³Microsoft Script Center´ and show you how to create user-defined functions and call them from a script. Dot Sourcing I find both methods useful but. whereas the filter has immediate access to the $_ variable and begins processing elements as they become available (streaming). Due to the $_ variable being able to process objects immediately. The function doesn¶t run until all data has been stored in the $input variable. I¶m going to show you both as I believe both methods have there own unique value. not the ³Function´ keyword. Modular Scripting 2. List Processor Information: $strComputer = ³.

provided by Microsoft.MediaType write-host ³Model: ´ $objItem.Caption write-host ³CPU Status: ´ $objItem.CurrentClockSpeed write-host ³Device ID: ´ $objItem.Status write-host } List Processor Information and List Disk Functions In this example we are converting the ListProcessor and the ListDisk scripts.Partitions write-host ³Size: ´ $objItem.DeviceID . into functions. Here are the syntaxes I¶ve used: Function ListProcessor {Script Block} -and.foreach ($objItem in $colItems) { write-host ³Description: ´ $objItem.CpuStatus write-host ³Current Clock Speed: ´ $objItem.DeviceID write-host ³Interface Type: ´ $objItem.InterfaceType write-host ³Media Type: ´ $objItem. the ³#´ symbol is used for comments.Size write-host ³Status: ´ $objItem.Function ListDisk {Script Block} Note: In PowerShell scripting.Description write-host ³Device ID: ´ $objItem.Model write-host ³Partitions: ´ $objItem.txt # ================================================================== =========== # FUNCTION LISTINGS # ================================================================== =========== # Function: ListProcessor # Created: [09/17/2007] # Author: Jesse Hamrick # Arguments: # ================================================================== =========== # Purpose: Provides Processor information # # # ================================================================== =========== function ListProcessor { $colItems = get-wmiobject -class ³Win32_Processor´ -namespace ³root\CIMV2 ` -computername $strComputer foreach ($objItem in $colItems) { write-host ³Caption: ´ $objItem. ListProcessor Function # FileName: ListProcessor.

txt #*================================================================= ============ #* FUNCTION LISTINGS #*================================================================= ============ #* Function: ListDisk #* Created: [09/15/2007] #* Author: Jesse Hamrick #* Arguments: #*================================================================= ============ #* Purpose: Provides Disk Information #* #* #*================================================================= ============ Function ListDisk { $colItems = get-wmiobject -class ³Win32_DiskDrive´ -namespace ³root\CIMV2 ` -computername $strComputer foreach ($objItem in $colItems) { write-host ³Description: ´ $objItem. They will enumerate the data on the local host. Building a Modular PowerShell Script I¶m going to write a script that enumerates the processor(s) and disk(s) properties.write-host ³L2 Cache Size: ´ $objItem. I¶ll ³snap-in´ my newly created functions and use the ³SCRIPT BODY´ section of the .InterfaceType write-host ³Media Type: ´ $objItem.Status write-host } } To verify functionality.L2CacheSize write-host ³L2 Cache Speed: ´ $objItem.Partitions write-host ³Size: ´ $objItem.Size write-host ³Status: ´ $objItem.Model write-host ³Partitions: ´ $objItem.Name write-host } } ListDisk Function #* FileName: ListDisk.MediaType write-host ³Model: ´ $objItem.L2CacheSpeed write-host ³Name: ´ $objItem.Description write-host ³Device ID: ´ $objItem.DeviceID write-host ³Interface Type: ´ $objItem. you can copy and paste the functions into PowerShell and call them from the command line by name.

com #* Reqrmnts: #* Keywords: #*================================================================= ============ #* Purpose: Computer Invetory of CPU and Disk Properties #* #* #*================================================================= ============ #*================================================================= ============ #* REVISION HISTORY #*================================================================= ============ #* Date: [DATE_MDY] #* Time: [TIME] #* Issue: #* Solution: #* #*================================================================= ============ #*================================================================= ============ #* FUNCTION LISTINGS #*================================================================= ============ . subroutines do not exist in PowerShell.powershellpro.template to control the function calls. 2. So. Here is what a modular script would look like: #* FileName: ComputerInv. Couple of differences: 1.meaning functions need to be declared before they can be called in the script. subroutines and functions.ps1 #*================================================================= ============ #* Script Name: [Computer Inventory] #* Created: [09/15/2007] #* Author: Jesse Hamrick #* Company: PowerShell Pro! #* Email: #* Web: http://www. were the whole script is read by the scripting host before it is executed. This may sound familiar to you if you have worked with VBScript. Functions in PowerShell provide the same functionality that both subroutines and functions did in VBScript. PowerShell parses scripts sequentially . This is unlike VBScript.

Description write-host ³Device ID: ´ $objItem.DeviceID write-host ³L2 Cache Size: ´ $objItem.DeviceID .L2CacheSpeed write-host ³Name: ´ $objItem.Caption write-host ³CPU Status: ´ $objItem.# Function: ListProcessor # Created: [09/17/2007] # Author: Jesse Hamrick # Arguments: # ================================================================== =========== # Purpose: Provides Processor information # # # ================================================================== =========== function ListProcessor { $colItems = get-wmiobject -class ³Win32_Processor´ -namespace ³root\CIMV2 ` -computername $strComputer foreach ($objItem in $colItems) { write-host ³Caption: ´ $objItem.CurrentClockSpeed write-host ³Device ID: ´ $objItem.L2CacheSize write-host ³L2 Cache Speed: ´ $objItem.CpuStatus write-host ³Current Clock Speed: ´ $objItem.Name write-host } } #*================================================================= ============ #* Function: ListDisk #* Created: [09/15/2007] #* Author: Jesse Hamrick #* Arguments: #*================================================================= ============ #* Purpose: Provides Disk Information #* #* #*================================================================= ============ Function ListDisk { $colItems = get-wmiobject -class ³Win32_DiskDrive´ -namespace ³root\CIMV2 ` -computername $strComputer foreach ($objItem in $colItems) { write-host ³Description: ´ $objItem.

ListProcessor # Call the ³ListDisk´ function. Modular scripting may not be the best solution for the example above.Size write-host ³Status: ´ $objItem. Again. the example was provided only to introduce the concept. With modular scripting. I declared the functions and used the ³SCRIPT BODY´ to snap the functions in place. ³dot-source´ means using dot-notation to call script blocks.write-host ³Interface Type: ´ $objItem. Let¶s say you want to change to order of the script. and/or aliases from within your script.InterfaceType write-host ³Media Type: ´ $objItem. we will use dot-notation to call scripts that exists outside the main script. that you maintain. you want to list the Disk Properties before the Processor Properties.´ # Call the ³ListProcessor´ function.Partitions write-host ³Size: ´ $objItem. Dot Source (Calling Scripts and Functions) Essentially.Model write-host ³Partitions: ´ $objItem. We¶re going to use the same script examples above. as your tasks become more complex so do your scripts. $strComputer = ³. Modular scripting is a great way to organize your scripts. You can ³snap-in´ new functionality to existing scripts as needed and easily control the flow of your script without having to move around large chunks of code.{} . You only need to reverse the order of the function calls in the ³SCRIPT BODY´ to make this happen. complex scripts become more manageable. The syntax used for dot-notation and scriptblocks is: . functions. It allows you to build from a user-defined functions library.MediaType write-host ³Model: ´ $objItem. but instead of calling the function written within the script.Status write-host } } #*================================================================= ============ #* SCRIPT BODY #*================================================================= ============ # Create a string variable using the local computer. ListDisk #*================================================================= ============ #* END OF SCRIPT: [Computer Inventory] #*================================================================= ============ Now you have a visual of a modular PowerShell script.

1. I¶m going to be working from the ³C:\MyScripts´ directory.Status write-host } Steps 1 and 2 are the same script blocks that we¶ve worked with in this PowerShell Article. Save this code as Disk. Save the following code as CPU.CpuStatus write-host ³Current Clock Speed: ´ $objItem.MediaType write-host ³Model: ´ $objItem. Now.L2CacheSize write-host ³L2 Cache Speed: ´ $objItem.ps1 in the MyScripts directory: $colItems = get-wmiobject -class ³Win32_Processor´ -namespace ³root\CIMV2 ` -computername $strComputer foreach ($objItem in $colItems) { write-host ³Caption: ´ $objItem.com #* Reqrmnts: #* Keywords: #*================================================================= .Model write-host ³Partitions: ´ $objItem. Calling a Script from within a Script In the first example.powershellpro.Example 1.CurrentClockSpeed write-host ³Device ID: ´ $objItem.Caption write-host ³CPU Status: ´ $objItem. Step 1.ps1 #*================================================================= ============ #* Script Name: [Computer Inventory] #* Created: [09/15/2007] #* Author: Jesse Hamrick #* Company: PowerShell Pro! #* Email: #* Web: http://www.ps1: $colItems = get-wmiobject -class ³Win32_DiskDrive´ -namespace ³root\CIMV2 ` -computername $strComputer foreach ($objItem in $colItems) { write-host ³Description: ´ $objItem.Size write-host ³Status: ´ $objItem.L2CacheSpeed write-host ³Name: ´ $objItem.Description write-host ³Device ID: ´ $objItem.DeviceID write-host ³Interface Type: ´ $objItem.ps1 scripts. #* FileName: ComputerInv_v1.ps1 and Disk. Step3: Modify the main script as follows: Remove the function(s) code from the script and modify the script body to call both CPU. let¶s modify our main script body to use dot-notation to call these scripts.Name write-host } Step 2.DeviceID write-host ³L2 Cache Size: ´ $objItem.InterfaceType write-host ³Media Type: ´ $objItem.Partitions write-host ³Size: ´ $objItem.

\Disk. By saving our scripts (code library) to this directory. Run the script: C:MyScripts\ComputerInv_v1. we only have to call the script name without possible path issues. By default. .0 .\CPU. PowerShell is installed using the following directory path: C:\WINDOWS\system32\WindowsPowerShell\v1.ps1<enter> This works great if we organize all of our scripts (code library) within the ³MyScripts´ directory.{. .1.ps1} # Use Dot-Source to Call the ³ListDisk´ function.\CPU. We can use the System Path to find the .ps1 files. The $PsHome variable provides the installation path of PowerShell.============ #* Purpose: Computer Invetory of CPU and Disk Properties #* #* #*================================================================= ============ #*================================================================= ============ #* REVISION HISTORY #*================================================================= ============ #* Date: [10/09/2007] #* Time: [9:30 AM] #* Issue: Dot-Source Example #* Solution: #* #*================================================================= ============ #*================================================================= ============ #* SCRIPT BODY #*================================================================= ============ # Create a string variable using the local computer.{. $strComputer = ³.ps1} #*================================================================= ============ #* END OF SCRIPT: [Computer Inventory] #*================================================================= ============ Since I¶m working from ³C:\MyScripts´ directory I can use ³.´ # Use Dot-Source to Call the ³ListProcessor´ function.ps1 to call the scripts in my code.

1.ps1} # Use Dot-Source to Call the ³ListDisk´ function.{CPU. . Let¶s move ComputerInv_v1.ps1} #*================================================================= ============#* END OF SCRIPT: [Computer Inventory] . Step 1. $strComputer = ³.´ # Use Dot-Source to Call the ³ListProcessor´ function.ps1 to the v1.1. Then modify the script body as follows: #* FileName: ComputerInv_v1. and Disk.ps1.powershellpro.{Disk.ps1 #*================================================================= ============ #* Script Name: [Computer Inventory] #* Created: [09/15/2007] #* Author: Jesse Hamrick #* Company: PowerShell Pro! #* Email: #* Web: http://www.Example 2. .com #* Reqrmnts: #* Keywords: #*================================================================= ============ #* Purpose: Computer Invetory of CPU and Disk Properties #* #* #*================================================================= ============ #*================================================================= ============ #* REVISION HISTORY #*================================================================= ============ #* Date: [10/09/2007] #* Time: [9:30 AM] #* Issue: Dot-Source Example #* Solution: #* #*================================================================= ============ #*================================================================= ============ #* SCRIPT BODY #*================================================================= ============ # Create a string variable using the local computer.ps1.0 directory. CPU.

CD to the root of C: drive and attempt to run the script again: C:\ComputerInv_v1.1. Touched on the differences between Functions and Filters. Functions and Filters provide many uses as we will discover as we progress. If your writing scripts for you own environment. With the script files being placed in the PowerShell install directory. You may wish to use the modular approach so that you can present your client will a single script that is well document.#*================================================================= ============ Here is the change in the script body .ps1 files if necessary Example 2. See you then« .ps1} to . Talked about how to define data types.ps1<enter> Did the script work? It will use the System¶s path to find the . Until next time.{. let¶s say you have one large file that contains over 100 separate functions you¶ve created. Essentially.ps1<enter> Now. Calling a Function from another script file. For example. you maintain your function library in one or two documents. These uses will become known throughout the rest of the tutorials. The system path will find the where the scripts are located and launch them.from . the purpose of this tutorial was the introduction of Functions and Filters and how they can assists with script organization.\scriptname. Click here to find out how« Which process should I use (Modular or Dot Source)? Do I write functions within the script or do I call other scripts outside the main script? There is really no wrong or right here. let¶s say you are writing a script for a client that will be utilizing functions in your script library. Passed arguments to Functions. Introduced the param keyword and the $args variable. Again. For example. The $input variable and the $_ variable. Explained how to set default parameters. Using ³dot-sourcing´ you could create a library of functions. Let¶s launch the Computer Inventory script: C:\MyScripts\ComputerInv_v1. chances are your using dot sourcing to call other functions as it takes less time and less code to accomplish the task« Conclusion In this PowerShell Training session we have: y y y y y y y y y Defined Functions and Filters.ps1} Step 2. happy scripting« tutorials. it depends on the situation. You can use dot sourcing to read the file and call one or more functions written in the file. Examples of using Functions to organize scripts and control script execution. we only have to type in the script name in which to run. Learned how to create and call Functions.{scriptname. we will be looking a Functions and more Script Block detail.1.

PowerShell Functions and Filters .The basics PowerShell Tutorial 10: Functions and Filters .

Sign up to vote on this title
UsefulNot useful