Back to description
If you are like me, then when you begin to look seriously at an interesting piece of software, you like to get your hands... more
If you are like me, then when you begin to look seriously at an interesting piece of software, you like to get your hands dirty and play with it from the beginning. In this chapter, I show you how to get started using Windows PowerShell, and I'll show you enough of the PowerShell commands to let you begin to find your way around effectively. In the rest of the book, I help you build on that initial knowledge so that you can use PowerShell for a wide range of useful tasks, depending on your requirements.
Windows PowerShell, as you probably already know, is Microsoft’s new command shell and scripting language. It provides a command line environment for interactive exploration and administration of computers, and by storing and running Windows PowerShell commands in a script file, you can run scripts to carry out administrative tasks multiple times. Windows PowerShell differs in detail from existing command line environments on the Windows and Unix platforms, although it has similarities to past environments. In Chapter 3, in particular, I explain more about the PowerShell approach, although differences from existing command shells and scripting languages will emerge in every chapter.
Once you have had a brief taste of PowerShell, you will need to understand a little of the assumptions and approach that lie behind the design decisions that have made PowerShell the useful tool that it is. In Chapter 2, I step back from using the PowerShell command line and look at the strengths and deficiencies of some existing Microsoft approaches to system management and then, in Chapter 3, take a look at the philosophy and practical thought that lies behind the approach taken in Windows PowerShell.
... less
In this chapter, I briefly look at how Windows command line tools developed and some of the reasons why a new command shell... more
In this chapter, I briefly look at how Windows command line tools developed and some of the reasons why a new command shell and scripting language are needed on the Windows platform. In Chapter 3, I discuss some aspects of the approach that Windows PowerShell takes, with the aim of improving on the current command shell and scripting languages available on the Windows platform.
Windows PowerShell wasn’t created in a vacuum. It has been created to fill a business need to allow administrators to work more effectively than the current command line and scripting tools on the Windows platform. Let’s look at why Windows command line tools have been relatively neglected for years and why there was a business need for a better tool.
The PowerShell team recognized many limitations of the existing Microsoft command line, GUI, and scripting tools which I... more
The PowerShell team recognized many limitations of the existing Microsoft command line, GUI, and scripting tools which I described in Chapter 2. The background against which the PowerShell team was working was changing significantly with a strategic move at Microsoft from COM (Component Object Model) programming to .NET Framework programming. It therefore made sense, going forward, for PowerShell to be based on the .NET Framework.
The move from COM-based programming to .NET Framework–based programming opened up opportunities to create a new approach to the command line and a new scripting language using the same commands and syntax as were available on the command line.
One of the most frequent and useful ways to put Windows PowerShell to work is from the Windows PowerShell command line. For... more
One of the most frequent and useful ways to put Windows PowerShell to work is from the Windows PowerShell command line. For example, when you use Windows PowerShell to perform ad hoc diagnostics on a system, you will typically use it interactively from the Windows PowerShell shell command line. To diagnose causes of unusual system behavior effectively, you need to find out what the conditions are that are likely causing problems. To do so, you need to explore the characteristics of the system in an interactive way, which is where the command line comes in. The information that you discover about one aspect of the system’s operation can help you focus subsequent commands that you issue. Of course, in some situations you may need to carry out similar diagnostic operations on multiple systems, and it makes sense to save at least some of the commands you use on the command line to a Windows PowerShell script file.
In this chapter, I show you how Windows PowerShell parses characters entered at the command line, so that you can understand the differences between command mode parsing and expression mode parsing. I also show you how to use Windows PowerShell commands to explore, from the command line, important information about the running of a Windows system.
Windows PowerShell allows you to configure several aspects that control what happens when you launch PowerShell and how PowerShell... more
Windows PowerShell allows you to configure several aspects that control what happens when you launch PowerShell and how PowerShell behaves after launching it. You can even add additional providers and cmdlets to those available by default.
To add further providers and cmdlets, you can load PowerShell snapins in addition to the core snapins that load by default when Windows PowerShell is started up. A snapin is a .NET assembly that contains Windows PowerShell providers and/or Windows PowerShell cmdlets.
You can create profile files that customize the behavior of every Windows PowerShell that you launch. Or you can customize behavior for each user individually.
You can also change the behavior of Windows PowerShell by using aliases. There are many practical advantages in PowerShell having a unique and consistent behavior. For example, once you become familiar with the verb-noun syntax convention, it becomes pretty easy to guess what the name of a command to carry out a particular task might be. However, there are also advantages in PowerShell having the flexibility to modify the behavior of the command shell to conform to user expectations or past experience. For example, by providing familiar commands (using aliases) PowerShell enables users who are familiar with other widely used command line shells to get up and running straightaway, since, at least in part, they can use commands they are already familiar with to achieve desired results.
In some situations, you can issue a Windows PowerShell command simply by using the name of a cmdlet or function. This, typically... more
In some situations, you can issue a Windows PowerShell command simply by using the name of a cmdlet or function. This, typically, results in the default behavior of the cmdlet. (If there is a required parameter, you are prompted to provide it.) The cmdlet behaves as if some implicit parameter has been supplied that specifies how the cmdlet is to execute. For example, if you issue the command
get-command
information about all available commands is displayed in the PowerShell console. The behavior is the same as if you issue either of the following forms of the command:
get-command *
or:
get-command –name *
In the two preceding commands, you supply a parameter value (in this case the wildcard *, which matches all command names) that specifies the commands for which information should be displayed.
In some situations, you need to name the parameter before you can supply a value for it. In such situations, the parameter is termed a named parameter. In other situations, you don’t need to provide a name for some parameters. The position of the parameter value in relation to the position of other unnamed parameter values determines how the PowerShell parser interprets the value that you supply. Parameters for which you can, but don’t need to, supply a name are termed positional parameters.
In this chapter, I cover two techniques that you may find useful to take control of your output. You look at how you can... more
In this chapter, I cover two techniques that you may find useful to take control of your output. You look at how you can take the potentially enormous amount of information returned from some cmdlets and how to format and filter that information.
Filtering determines whether or not an object is passed on to the next step in a pipeline. You invoke filtering by using some cmdlets and specifying tests that determine what objects to pass along the pipeline. The where-object cmdlet is a powerful tool for filtering according to a test specified in a Windows PowerShell expression. You can also use the select-object cmdlet to select specified properties to be passed along the pipeline.
where-object
select-object
Formatting is concerned with the display of information, both in general and in determining where the objects are supplied to the final step in a pipeline. In many of the pipelines you have seen so far, there has been an invisible final step that uses the default formatter to define how the results of a command or pipeline are displayed. However, the default formatter doesn’t always format the output in the way you need. Windows PowerShell provides two cmdlets, format-table and format-list, which allow you to take more control of the display of the information in objects that emerge from earlier steps in the pipeline.
format-table
format-list
Tools such as Windows PowerShell provide tremendous power. But at the same time, one potentially terrifying thing about Windows... more
Tools such as Windows PowerShell provide tremendous power. But at the same time, one potentially terrifying thing about Windows PowerShell is that its power makes it potentially more destructive if you do something wrong. Imagine that you want to delete some files or stop some processes or services depending on the value returned by an expression. You really need to be sure of what you are doing, don’t you? You don’t want to end up deleting some crucial files on which your company depends just because you made a mistake in the syntax on the command line or in a Windows PowerShell script.
The Windows PowerShell designers have that base covered by providing several options to use with cmdlets that let you check the effects of what you plan to do. I describe these options in this chapter.
There are three parameters available for use with many, but not all, Windows PowerShell cmdlets that allow you to anticipate exactly what a command will do or monitor what a command has done. The cmdlets that lack these parameters cannot change system state. The parameters are:
whatif Allows you to see what a command would have done without actually executing the command
whatif
confirm Allows you to see the individual actions a command would have taken and allows you to confirm or cancel each action
confirm
verbose Allows you to see in detail what you have done
verbose
Some of the examples in this chapter are potentially damaging to your system. Please be VERY CAREFUL when you type the code examples to ensure that you do not unintentionally run potentially damaging code. And when you extend or adapt the examples, make liberal use of the -whatif parameter to check that your adaptations don’t have unintended effects.
-whatif
In addition, while you are learning the effects of Windows PowerShell commands, you may want to focus your experimentation on a test machine.
Windows PowerShell allows you readily to access, retrieve, and manipulate data from a range of drives, files, and other data... more
Windows PowerShell allows you readily to access, retrieve, and manipulate data from a range of drives, files, and other data containers. Access to data stores in Windows PowerShell is founded on providers. A provider is a .NET program that makes available data from a data store and supports viewing and manipulation of that data.
In this chapter, I introduce you to several cmdlets that are relevant to exploring data stores and retrieving and manipulating data from them.
One of the differences between the Windows and the Linux families of operating systems is that Windows and Windows applications store system information in a huge variety of formats. In Linux, a lot of information is stored as text and, if you have the appropriate text utilities and the skills to use them, you can access a lot of system information by simply manipulating text. In Windows, you have system information stored in stores such as the registry and Active Directory. Text utilities just won’t cut it. Windows PowerShell provides, and needs, a range of providers that allow you to access and manipulate objects that represent a variety of data stores.
In the preceding chapters, I illustrated the functionality of individual cmdlets but put little emphasis on using Windows... more
In the preceding chapters, I illustrated the functionality of individual cmdlets but put little emphasis on using Windows PowerShell as a scripting language. In this chapter, I introduce several aspects of the Windows PowerShell language that make it suitable for scripting, and describe and demonstrate how many of its various components can be used. This foundational understanding of the PowerShell scripting language, taken together with your understanding of the various cmdlets, built up in the preceding chapters, will give you the knowledge necessary to explore in the following chapters the range of ways that Windows PowerShell can be used.
Chapter 11 introduces several more features of the Windows PowerShell language.
In this chapter, I continue describing Windows PowerShell language constructs that are available to you for use in Windows... more
In this chapter, I continue describing Windows PowerShell language constructs that are available to you for use in Windows PowerShell scripts. I cover the following topics:
Arrays
Associative arrays
Conditional expressions
Looping constructs
The add-member cmdlet
Windows PowerShell is designed primarily to work with .NET objects, but it also has enormous power and flexibility for the... more
Windows PowerShell is designed primarily to work with .NET objects, but it also has enormous power and flexibility for the processing of text. In this chapter, I show you techniques that you can use to process text using Windows PowerShell commands and scripts.
If you have worked through earlier chapters, you will be aware that Windows PowerShell cmdlets emit objects and not strings. In that respect, Windows PowerShell cmdlets differ substantially from traditional executables such as those which form part of the traditional cmd.exe command shell. If you use Windows PowerShell cmdlets, you need to be able to process the objects those cmdlets emit. However, from the Windows PowerShell command shell, you can also use traditional applications that emit strings. If you use those applications and utilities and need to process the strings they emit, then the string manipulation capabilities of Windows PowerShell may be very useful. Textual data arises from many other sources, and you will likely at some time want to manipulate text using at least some of the techniques I show you in this chapter. If you commonly manipulate text data, you will use these techniques regularly when you use PowerShell.
cmd.exe
Windows PowerShell is designed primarily to make use of the .NET Framework and its associated classes. However, it is going... more
Windows PowerShell is designed primarily to make use of the .NET Framework and its associated classes. However, it is going to take some time and presumably several versions of Windows PowerShell before all of a system will be exposed to Windows PowerShell as cmdlets. The Windows PowerShell team has suggested a period of 3 to 5 years for the transition to .NET and system coverage by cmdlets to be completed. Therefore, when using version 1 of Windows PowerShell and for some time afterward you are likely to want to (or have to) continue to make use of existing approaches, including the manipulation of COM objects. After all, even when there is a choice in a future version of Windows PowerShell, why should you always throw away your existing working code? The support for COM automation in Windows PowerShell means that you can leverage your existing knowledge of COM objects that are relevant to your needs.
In this chapter, therefore, I introduce you to working with COM objects from Windows PowerShell. While for some COM objects there are Windows PowerShell cmdlet equivalents, for many there are not. Well not yet anyway. If your existing COM-based code works well, you may want to postpone updating that code or writing new code.
Not all COM objects are supported in Windows PowerShell version 1. For example, COM objects which are based on CDO (Exchange Collaboration Data Objects) are not supported in version 1.0.
Windows PowerShell is based on and leverages extensively version 2.0 of the .NET Framework. This means that you can use Windows... more
Windows PowerShell is based on and leverages extensively version 2.0 of the .NET Framework. This means that you can use Windows PowerShell for an enormous range of scripting functionality, taking advantage of the huge range of.NET Framework classes to provide the functionality you need to create custom scripts.
Limitations in version 1.0 of Windows PowerShell tend to reflect the fact that many facets of the Windows operating system are not yet exposed as managed objects. It is likely that an increasing proportion of a Windows system will be exposed as .NET objects in future versions of the .NET Framework and, subsequently, in future versions of Windows PowerShell. In the meantime, Windows PowerShell can be used with existing technologies where .NET classes aren’t available. In Chapter 13, for example, I showed you how to work with COM objects from Windows PowerShell.
One of PowerShell’s goals is to enable system administrators to find out what is happening on one system or, more usefully... more
One of PowerShell’s goals is to enable system administrators to find out what is happening on one system or, more usefully, on large numbers of systems. In this chapter, I explore techniques that allow you to use Windows PowerShell to find out what is happening on a system.
Of course, PowerShell isn’t the only tool available to explore a Windows system. There are many other tools available from Microsoft and elsewhere that allow you to explore at least some aspects of what a system is doing. PowerShell is one tool in an armory, not the whole arsenal. But it’s a very useful tool for exploration, partly for what it can do, partly for the convenient and interactive way that you can explore a system from the command line.
For example, if a machine has been showing sluggish performance, you might want to know what processes are running, how much CPU time they are using, and how much memory they are using. You can find out much of that information from Windows Task Manager, but it can be tedious either to scroll around within that utility’s pretty constricted interface to change the columns to be displayed, or to scroll around an uncomfortably large number of columns to see the information you want. PowerShell lets you select and filter the information you want, display the parts of it that interest you onscreen and, if you want, send exactly the information you chose for your purposes to a file.
Similarly, you might want to know about services registered on a machine. Are the expected services running, for example? Or you might want to be able from the command line to stop and start a service.
If you have worked through earlier chapters of this book, you will have begun to understand the huge potential that Windows... more
If you have worked through earlier chapters of this book, you will have begun to understand the huge potential that Windows PowerShell has for inspecting and manipulating Windows computers. Any software that allows you to discover what is happening on a system and modify that system and what is stored in its files has enormous power. That gives you power to do good. But with power also comes risk.
The designers of Windows PowerShell have spent significant time to analyze those risks. As a result, Windows PowerShell has an execution policy that, by default, prevents you running any PowerShell scripts. This is part of an approach that Microsoft calls Secure by Default. When you install the product, it is intended to be secure. This means that you need to take active steps to enable features that you want. In PowerShell executing scripts is a prominent example.
What is the reason for the Secure by Default approach? Imagine the scenario where you have just installed PowerShell and downloaded a script from the Internet or are sent a script by an acquaintance. With your possibly limited understanding of PowerShell, the risk of your running a malicious script has to be there. That script could remove files from your hard drive or run other scripts, and those scripts, in turn, could be malicious. The potential for damage is obvious. The security policies for Windows PowerShell are designed to allow you to configure security intelligently once you understand the implications of your actions, so that you find the appropriate balance between security and functionality for your business scenario(s).
If you’re going to be able to persuade your managers that installing Windows PowerShell widely is a safe thing to do, then you need to understand what protections are in place and how to make the appropriate adjustments to address your company’s business scenario.
One of the realities of life when you’re working with computers is that, no matter how careful you are, something is going... more
One of the realities of life when you’re working with computers is that, no matter how careful you are, something is going to go wrong somewhereand things will go wrong sufficiently often that it’s important to recognize and prepare for the possibility. For this reason, it makes sense to provide Windows PowerShell with functionality to monitor and respond intelligently to error conditions. And that’s what the Windows PowerShell team have done.
This chapter introduces the way Windows PowerShell treats errors and shows you how to retrieve information about errors and how you can change the way Windows PowerShell responds to errors and exceptions.
Writing error-free code is the aspiration of pretty much every programmer. If you’ve spent any significant amount of time... more
Writing error-free code is the aspiration of pretty much every programmer. If you’ve spent any significant amount of time writing programs of any kind, you’ll know that writing error-free code becomes increasingly difficult as the size of your code increases.
When you use Windows PowerShell on the command line, identifying many errors is simply a matter of spotting some slight syntax error. But Windows PowerShell is a scripting tool as well as a command line shell, so as with any significant programming language, you will need to carry out at least some debugging of your code when writing Windows PowerShell scripts. The longer and more complex your PowerShell scripts become, the more demanding it is to identify and fix all the errors that are present in them.
Debugging is the process of trying to identify and correct bugs in PowerShell scripts or commands. Often during initial development of a script you will observe undesired behavior of some kind. Spotting what is wrong can be easy or it can be hugely time-consuming and sometimes frustrating.
You might fail to spot some types of errors because you don’t test edge conditions. Until users run your scripts in conditions you hadn’t anticipated, the code seems to run correctly. When users bring an unanticipated combination of conditions to code execution, previously unknown errors may surface. I don’t propose to explore those issues in depth in this chapter but will focus primarily on issues that are specific to the debugging of PowerShell and its scripts.
Windows PowerShell provides cmdlets to allow you to work effectively with drives, folders, and files on the file system.... more
Windows PowerShell provides cmdlets to allow you to work effectively with drives, folders, and files on the file system. Windows PowerShell supports identification of drives using the get-psdrive cmdlet and exploration of files and folders using the get-childitem cmdlet. You can also create new drives, folders, and files. There is also a group of cmdlets that allow you to read and write content to and from text files.
get-psdrive
get-childitem
Access to folders and files using Windows PowerShell is supported by the FileSystem provider. Additional command shell providers provide access to the HKLM (HKey_Local_Machine) and HKCU (HKey_Current_User) hives in the registry as well as drives for aliases, certificates, environment variables, functions, and variables. The command shell providers are in the Microsoft.Management.Automation.Core namespace.
FileSystem
HKey_Local_Machine
HKey_Current_User
Microsoft.Management.Automation.Core
If you want to find all providers supported on your system use the command:
get-psprovider
or, to find information about each drive and its associated provider, use this command:
get-PSdrive -Name * |
Windows PowerShell provides several command shell providers that allow you to work with data stores in a similar way to the... more
Windows PowerShell provides several command shell providers that allow you to work with data stores in a similar way to the ways you can work with the file system when using CMD.exe. By using a familiar file system metaphor, you should be able to navigate effectively in other hierarchical data stores without difficulty, assuming that you understand the structure of the store. Among the data stores that Windows PowerShell allows you to access in this way are the HKLM (HKey_Local_Machine) and HKCU (HKey_Current_User) hives of the Windows registry.
CMD.exe
HKey
Local
Machine
Current
User
Windows PowerShell provides cmdlets to allow you to explore two registry hives and to alter the values held in registry keys. This functionality is powerful and flexible but, as with everything relating to the registry, you need to proceed with caution. If you make inappropriate changes to the registry, it is certainly possible to end up with a machine that won’t run correctly or may not run at all. So be warned. Make changes to the registry only when you understand the implications of what you are doing. And check carefully for typos and other errors before you commit a change.
Like the file system and registry, Windows PowerShell provides a command shell provider and corresponding drive that allows... more
Like the file system and registry, Windows PowerShell provides a command shell provider and corresponding drive that allows you to explore and manipulate environment variables. An environment variable is a value that can affect how the operating system or processes run.
Working with environment variables is simpler in some respects than working with the file system or the registry, since the environment variables are not stored in a hierarchy inside the env drive unlike the hierarchy of objects in the file system or registry. In the env drive, it is as if all Windows files were stored in the root folder. It is inappropriate, then, for example, to use the Recurse parameter when using the get-childitem cmdlet in the env drive that you might use with a drive associated with the FileSystem provider.
env
root
Recurse
Another limitation when using the env drive is that you cannot make permanent changes in environment variables. Changes you make to environment variables are limited to the duration of the relevant MSH session and apply only to that session.
A common administrative task is checking or examining event logs. Event logs contain useful information about the execution... more
A common administrative task is checking or examining event logs. Event logs contain useful information about the execution of the Windows system, of applications on a machine and whether any security issues have occurred. The event logs have a series of categories (entry types) that indicate the significance of the event being logged.
Windows PowerShell version 1.0 provides one cmdlet that supports event logs: the get-eventlog cmdlet, which displays information from the local machine.
get-eventlog
In Windows PowerShell version 1.0, the range of available cmdlets is significant, but they cover only part of the tasks that... more
In Windows PowerShell version 1.0, the range of available cmdlets is significant, but they cover only part of the tasks that a fully developed administrative command shell and scripting language need to cover. To fill that potential gap the PowerShell approach in version 1.0 includes support of existing technologies until such time as later versions of PowerShell provide fuller system coverage. In fact, PowerShell may continue to support existing technologies for longer than is strictly necessary, but in version 1.0 that support of legacy technologies is essential to plug the gaps that version 1.0 PowerShell cmdlets don’t cover.
Another approach used alongside the Web distribution of PowerShell 1.0 is the release of specialized cmdlets designed for specific problem domains. The first such group of cmdlets is intended for use with Microsoft Exchange 2007. It is likely that other Microsoft management technologies will later have their own set of functionally related cmdlets.
One of the most important ways that PowerShell exploits existing technologies is to allow developers access to Windows Management Instrumentation, WMI, through the get-wmiobject cmdlet. One gap in PowerShell version 1.0 functionality is that the cmdlets in the PowerShell Web release can access resources only on the local machine. To access remote resources using PowerShell, it is initially necessary to make use of legacy technologies. Windows Management Instrumentation provides a way to achieve access to resources on remote machines.
get-wmiobject
Depending on your preferences or current knowledge (or already existing WMI scripts), you may opt to use PowerShell exclusively for what it already does in version 1.0 or progressively transition WMI scripts that use VBScript to a PowerShell context where the functionality in PowerShell version 1.0 makes that transition possible. However, if you need to access remote machines on your network, you have to use the get-wmiobject cmdlet in PowerShell version 1.0, since PowerShell doesn’t natively support remote machine access.
Purchase Before purchasing this product, please be sure you have met all software and system requirements, and that you understand any limits placed upon its use.
Return Policy Wrox Chapters on Demand are non-returnable and non-refundable.
Reader Software Wrox Chapters on Demand are offered as PDFs, and they must be viewed using the Adobe Reader. If you do not have the Reader installed, it can be downloaded for free at Adobe.com.
Test Download As Wrox Chapters on Demand purchases are non-returnable, it is advisable that you test your system and software configurations with a free sample download before you place an order.
Usage Rights for a Wrox Chapter on Demand File Any Wrox Chapter on Demand product you purchase from this site will come with certain restrictions that allow Wiley to protect the copyrights of its products. After you purchase and download this title, you:
If you have any questions about these restrictions, you may contact Customer Care at (877) 762-2974 (8 a.m. - 5 p.m. EST, Monday - Friday). If you have any issues related to Technical Support, please contact us at 800-762-2974 (United States only) or 317-572-3994 (International) 8 a.m. - 8 p.m. EST, Monday - Friday).
Related Books