Chapter 2. PowerShell scripting overview
When you start using PowerShell’s scripting language, it’s easy to run into a number of gotchas and hurdles that you wouldn’t ordinarily see when you’re running commands. In this chapter, we’ll try to get those hurdles out of the way up front, so that you can start creating tools with fewer hassles.
From our perspective, PowerShell is first and foremost a command-line interface (CLI). That means you run commands and get immediate results. Like many good CLIs, PowerShell contains a scripting language, but using that language is optional. To make tools, we’ll definitely be using that language! The good news is that compared to languages like VBScript, Perl, PHP, and others, PowerShell’s language is incredibly simplified, consisting of only about three dozen keywords.
At its simplest, scripting might just involve running several specific commands in a specific sequence. More complex scripts might start applying logic—only execute this command if that condition exists. Scripts might have to execute some task across a number of different targets—checking a number of different files, reconfiguring a number of different services, and so on. The point is automation, in most cases, typically completing some series of steps that you could do manually but that you’d rather codify into a tool that can be reused and repeated more easily, perhaps by folks other than yourself.
PowerShell goes to some lengths, by default, to prevent scripts from executing. That’s mainly because in the past (think VBScript era, here) scripts were used maliciously. A detailed discussion of PowerShell security is out of scope for this book; you should already be familiar with the execution policy, what it does, and what setting is appropriate for your organization. If you’re not, review the help for PowerShell’s Set-ExecutionPolicy command, including the “See Also” help files that it references. You can also refer to the “Security Alert!” chapter in Learn Windows PowerShell v3 in a Month of Lunches, which includes a more detailed discussion of PowerShell’s security concepts and mechanisms.
For now, you need to decide which execution policy is right for you in terms of this book’s hands-on labs. Ideally, you’ll be working in a standalone, isolated virtual machine, giving you the ability to set your execution policy to RemoteSigned or Unrestricted without any potentially negative consequences. You should also know what your production environment’s execution policy is and take the time to think about how that will affect the script-based tools that you’ll create and use in that environment.
If you’re writing scripts, then it goes without saying that you’ll want to run them. This is where another PowerShell security feature can create a gotcha. As shown in figure 2.1, you can’t simply type the name of a script file in order to run it. Even with the execution policy configured to permit scripts, you must precede the script filename with a path. In figure 2.1, you’ll see the .\path in use, which refers to the current directory. You could also provide any other absolute or relative path in order to run a script—but you must provide a path of some kind.
If you’re working in the PowerShell ISE—and we expect that you’ll spend most of this book doing so—then you can click the green Play icon to run whatever script is open in the current tab. Figure 2.2 shows what this looks like and how you can configure the ISE to display both your script and its output in different panes.
Note that the one way you can’t run scripts, at least by default, is to double-click them in Windows Explorer. The .PS1 file type, which is used for PowerShell scripts, isn’t configured as an executable file type. Again, that’s a security precaution, so that double-clicking a script opens it in Notepad rather than running it. We don’t recommend changing that setting.
Scripts, you’ll notice, continue to use a .PS1 filename extension even though they’re running under PowerShell v3. The 1 designates the version of PowerShell’s scripting language, which hasn’t really changed since PowerShell v1.
Whatever you do, please don’t use Notepad to edit PowerShell scripts. Notepad might be free, but it does nothing to make the process easier. What’s far better, and equally as free, is the PowerShell ISE, which was shown in figure 2.2. Version 3 of the ISE (which comes with PowerShell v3) is robust, offers numerous handy features like IntelliSense code completion, and color codes your commands to help you make sure you’re typing them correctly. For example, as shown in figure 2.3, the ISE uses IntelliSense pop-up menus to help you complete command names more quickly—and to help prevent typos.
We strongly encourage you to get used to this feature, pressing Enter or Tab to select an item from the menu rather than typing entire command names manually. What you don’t type, you can’t mistype!
Try it Now
Now’s a good time to dive into the ISE and start trying this feature. It’s new in version 3, so if you don’t see the IntelliSense menus, you need to install PowerShell v3.
Figure 2.4 shows another ISE feature: parameter completion. Just type a command name, a space, and a dash, and the ISE prompts you with all of that command’s available parameters. Again, you can’t mistype what you don’t type, so choosing a parameter from the list will ensure that it’s typed correctly and completely and that it’s a legitimate parameter for that command.
Figure 2.5 shows how the ISE can help you prevent errors, too. Notice the squiggly red underline (we’ve added an arrow to point it out)? That’s telling you that there’s a syntax problem. In this case, it’s because we typed a comma but didn’t type anything after it. This is a great feature that helps you avoid error messages later: Just make sure you clear up all the red squiggles, and you’re one step closer to an error-free script!
You should pay close attention to the ISE’s color coding, because it’s another way the ISE can cue you to potential errors. For example, figure 2.6 shows a command we’ve typed incorrectly, forcing the ISE’s color coding to be incorrect and displaying a red squiggle. By getting used to what the colors should be, you’ll become more alert to errors when the colors look wrong.
Color coding errors can also come from improperly paired elements, like curly brackets, quotes, and so on. Just look for the spot where the color goes wrong—it’ll often be accompanied by a red squiggle—and that’s close to where you’ll need to put your fix. As shown in figure 2.7, the ISE goes a step further by highlighting matching paired elements. For this example, we put our cursor right next to a closing curly bracket, and the ISE subtly highlighted it and its pairing opening bracket. That helped us make sure that everything was properly nested, closed, and error free.
Note
It can be tough to see some of the ISE’s more subtle visual features in a black-and-white book—so we encourage you to retype these examples in the ISE yourself, so that you can more clearly see what’s happening. Also, keep in mind that you can select the Options item from the ISE’s Tools menu to customize the color coding, in case you find some elements too low contrast to read comfortably.
Of course, the ISE isn’t the only game in town. Numerous free editors—Notepad++ is one that folks often turn to—provide color coding for PowerShell scripts, although color coding is really the least of the features the ISE provides. There are also many commercial and free editors that provide more specific PowerShell support along the lines of the ISE. Some of the major choices include these:
- PowerShellPlus by Idera (http://idera.com)
- PrimalScript by SAPIEN Technologies (http://primalscript.com)
- PowerShell Studio (formerly PrimalForms) by SAPIEN Technologies (http://primaltools.com)
- PowerGUI (free and commercial Pro edition) by Quest Software (http://powergui.org and http://quest.com/powershell)
- Admin Script Editor (http://adminscripteditor.com)
- PowerSE (free and integrated with the commercial PowerWF product) by DevFarm Software (http://powerwf.com).
We don’t intend this as a comprehensive list, merely the major titles we’re aware of at the time of this writing. Concentrated Technology made a pretty detailed comparison of many of these, which you’ll find at http://Library.ConcentratedTech.com. Note that, as of this writing, PowerGUI doesn’t seem to be under active development, although it’s still in wide use by administrators everywhere. We weren’t able to evaluate its compatibility with PowerShell v3, though. Most of the commercial tools are available in a free trial, which often extends to 30 or 45 days, giving you ample time to try them all and decide which, if any, you like.
You’ll start this book with a simple lab: Make sure you can get the ISE open. Enter, save, and run a simple script (like Write-Host "It's working!") to make sure your execution policy is set properly. There’s no sample answer for this lab, because all you’re doing is verifying base PowerShell functionality.
Also ensure that you’re running PowerShell v3: If your ISE doesn’t look a lot like our screen shots and doesn’t provide the pop-up IntelliSense menus, download version 3 (it’s in the Management Framework package) from http://download.microsoft.com.