This is a book for system administrators, those who manage administrators, those responsible for auditing systems, and anyone else who needs to discover information about Windows-based systems. PowerShell and WMI are powerful individually, but when they come together they supply an unrivalled way to access and administer your systems.
I have attempted to show the breadth of problems that PowerShell and WMI can solve. The depth of these technologies is also exposed by the detailed and practical examples. There are areas such as clustering and the System Center family that haven’t been touched because of space considerations.
This book was written during the PowerShell v3 development and beta program. Except where otherwise stated, this book deals with PowerShell v2. Chapters 18 and 19 require PowerShell v3 as they use functionality only available in that version.
My development environment is Windows 7 and Windows Server 2008 R2, but I have also tested on Windows Server 2003 and Windows Server 2008 where possible.
Most of the code will also run on PowerShell 1.0, and I will point out where this is not the case and what alternatives are available.
This book isn’t a pure cookbook of PowerShell-based scripts nor is it a book on Windows administration. It lies between these two points and provides insight into how to automate the administration of your Windows systems using PowerShell and WMI.
You may not choose to read this book from cover to cover, but I urge you to keep it on your desk. I hope you will find yourself referring to it on a frequent basis. Once you start automating, the possibilities are only limited by your knowledge, and this book’s task is to supply you that knowledge along with appropriate examples so you can apply it to your environment.
The scripts are presented as techniques with problem, solution, and discussion sections. They should help you solve your particular problems. If they don’t, a message on the Author Online forum will reach me, and I may be able to supply some pointers. But no promises, because I have a day job as well.
This book is primarily for that overworked, and undervalued, person—the IT administrator. As an administrator, you may well find yourself constantly bombarded with new requests, new technologies, and user problems, and you may want to automate some of those tasks but not know where to start. Even some simple tools that could discover the configuration of the server that your predecessor built but didn’t document would be a help.
This book won’t solve all of your problems, but it will help you start to automate some of those problem areas. Make sure your manager reads chapter 1. They will then see what you are trying to achieve and how using the techniques in this book will make them look good as well.
The sample code in the book is based on real-world examples—I use a lot of scripts based on these techniques in my job. I have combined many of the discovery scripts, for example, to create a script that completely documents my servers. Take the code, experiment (in a test lab), and discover how you can start automating now.
PowerShell and WMI is divided into three parts. The book starts with an overview of the PowerShell and WMI technologies in part 1, “Tools of the trade.” This introductory section covers the overall problems you need to solve, provides an overview of PowerShell and WMI, and offers some best practices.
Chapter 1 describes the challenges we face every day as administrators—increasingly complex environments, new applications, fewer staff, and tighter deadlines. A quick look at PowerShell and WMI shows how they can be used to solve these problems and recover at least some of the time we need to become proactive in our approach.
Chapter 2 provides an overview of PowerShell. The use of cmdlets at the PowerShell prompt is described, followed by an introduction to how PowerShell uses .NET and how we can utilize some of the .NET functionality with PowerShell. Don’t worry, this isn’t going to become a developers’ book! PowerShell also has a scripting language that supplies the framework for our code. Simple scripts are described, leading up to the advanced functions we’ll be working with throughout the book. This chapter also supplies an overview of PowerShell remoting and jobs.
WMI is the other technology we’ll be using, and it moves to center stage in chap-ter 3. This is the most theoretical chapter in the book, because we delve into the structure of WMI, discovering how to document providers, namespaces, and classes. Examples of using the five WMI cmdlets are presented, together with some of the issues that may cause problems (workarounds are also presented). WQL is an SQL subset that can be used to query the WMI repository. Using WQL may seem like an old fashioned way of working, but it’s still required in a number of scenarios. A good working knowledge of WQL will help in the later chapters of the book. WMI maintains links, known as associators and references between many classes. These links can be used to make administration easier, so we’ll spend some time discovering how to use them.
Part 1 closes with chapter 4. This chapter covers a number of topics that will help you get the most out of PowerShell and WMI. It starts with finding code examples and ensuring that they’re safe to use. This leads into the topic of securing the PowerShell environment, including the digital signing of scripts. The section on optimizing PowerShell looks at data input and output, format files, simple debugging techniques, and error handling. WMI best practices, including the configuration of WMI-related settings, authentication within WMI, data filtering, and conversions bring the chapter to a close.
The bulk of the book is taken up by part 2, “WMI in the Enterprise.” A number of the chapters in this section discuss using WMI events. By using events, you can perform actions such as these:
WMI has traditionally been viewed as a method of gathering information about your system’s configuration. Chapter 5 demonstrates how this can be achieved using PowerShell and WMI. Techniques for discovering system configuration information, including hardware, operating system, and installed software are presented.
This theme continues into chapter 6, where you’ll discover how to investigate the storage systems installed in your servers. The WMI classes that enable you to work with, and discover information about, disk controllers, physical and logical disks, volumes, and mount points will be utilized and explained. Administering disks in terms of formatting and defragmenting disks will also be discussed.
In chapter 7, our attention turns to the registry. The usual warnings regarding registry modifications having the potential to destabilize your system still apply. Techniques to discover the registry size, administer registry keys and values, and work with security settings will be discussed.
The other major data store that administrators work with on a regular basis is the filesystem—this is the subject of chapter 8. WMI can’t be used to create filesystem objects, but it can be used to search for files and folders on local and remote machines. This becomes especially useful when we want to discover files or folders with special attributes, such as being hidden. Techniques to compress (and uncompress) files and folders are presented before we move on to examining the security settings on filesystems. The chapter closes with a look at file shares, with code that can be used to automate their whole lifecycle.
A server isn’t just a collection of hardware. In many cases, our main interest in a system is the applications that are running on that system. These are investigated in chap-ter 9, when we turn our attention to services and processes. The service health of a system (whether the correct services are running) and service load order are investigated. The whole process lifecycle from creation through administration to destruction can be managed with the PowerShell and WMI techniques presented in this chapter.
The one subject that’s guaranteed to upset every administrator at some time in their career is printing. Chapter 10 discusses printers. It starts by showing how to discover printer configuration and status, followed by a look at printer drivers. The chapter then examines how to manage printers and print jobs. The final part of the chapter discusses troubleshooting printers and shows how to perform tests, such as sending a test page to the printer.
Networking is the subject of chapter 11. Discovering the physical configuration of the network adapters, their IP addressing configuration, and the protocols in use forms the first part of the chapter. This is followed by sections on managing the physical adapters, configuring IP addresses, and related information. The chapter closes by examining how to discover the IPv4 routing table.
IIS is a common component of the Windows infrastructure. The IIS WMI provider is the subject of chapter 12. The chapter demonstrates how to administer the web server configuration, the website lifecycle, application pools, and web applications. The IIS WMI provider requires us to use a number of specialized techniques, which are explained in detail.
Configuring new servers is the subject of chapter 13. We’ll look at how to rename a server and perform the domain join operation. Network configuration using the techniques from chapter 11, setting the license key, and activating the operating system are all discussed. The final part of the chapter explains how to configure power plans.
Security should always be an important consideration, and in chapter 14 we’ll consider the users who have access to our systems, together with a number of other security-related issues. After you’ve discovered how to work with the local users and groups on the system, we’ll examine the antimalware status. The chapter closes with techniques for working with the firewall state and settings.
Windows is an event-driven operating system. In chapter 15, techniques for working with the event logs are presented. WMI can only work with the classic event logs, but we can discover event log sources and back up the event logs. Simple scheduled jobs and performance counters are discussed. In later versions of Windows, system assessments and a stability index can be produced, and these can be accessed by PowerShell and WMI. Accessing this information is an easy way to determine whether a particular system component isn’t performing or is affecting system stability.
Chapter 16 is a bit different in that we use the Hyper-V PowerShell library, which is based on WMI, to work with virtual machines. Techniques to create and configure remote machines, control virtual machines, start a group of virtual machines in sequence, and administer virtual disks are presented. This chapter is a good example of what many administrators do automatically—take the tools that are provided and build a wrapper to do exactly what they need in their environment.
In part 3, “The future: PowerShell v3 and WMI,” we take an in-depth look at some of the exciting new functionality associated with PowerShell and WMI; namely, using WMI over the WS-Management protocols and the introduction of CIM cmdlets and “cmdlets-over-objects” in PowerShell v3.
Chapter 17 examines the WSMAN cmdlets. Using these, it is possible to access the WMI provider from the WinRM service on the remote machine. This enables the retrieval of information and the configuration of the remote machine. It’s possible to perform just about any task through the WSMAN cmdlets that you could using the WMI cmdlets. The advantage is that you bypass DCOM, become firewall friendly, and potentially can access CIMOM (other non-Windows WMI providers) instances on non-Windows systems. The disadvantage is that it involves a more complex coding syntax and that you’re not dealing with live objects.
Chapters 18 and 19 should be read together, with the content in chapter 19 building directly on that in chapter 18. The starting point is new functionality in PowerShell v3 that enables you to wrap a WMI class in XML and use the resulting file as a PowerShell cmdlet—this is known by the catchy title of “cmdlets-over-objects.” The cmdlet is loaded into PowerShell as a module, and parameters are added to the cmdlet to provide filtering and search options. Two or more WMI classes can be treated this way, and the resultant cmdlets are loaded by creating a module file that calls them as submodules. Format and type files are also added to the module to control the formatting of the output.
In chapter 19, WMI methods are added to the mix. These drive the creation of additional cmdlets that are again loaded as part of the module. The ability to “cmdletize” WMI classes gives a huge boost to the ease of use. Much of the new PowerShell functionality in Windows Server 8 is produced in this manner.
Chapter 19 continues with the CIM cmdlets. These are analogous to WMI cmdlets but use a new API and new .NET objects. The CIM cmdlets are compared and contrasted to the WMI cmdlets to provide a context for their use. These CIM cmdlets combine the firewall friendliness of the WSMAN cmdlets and the ease of use of the WMI cmdlets. The chapter, and the book, closes with a review of CIM sessions, which can be thought of as similar to PowerShell remoting sessions. CIM sessions create a persistent connection to a remote machine to make multiple calls more efficient. They can work over WSMAN or DCOM to enable access to systems running PowerShell v3 or v2.
There are four appendices to the book. They supply a PowerShell reference guide, a WMI reference guide, a best practices guide, and a list of references that can be consulted for further information.
The source code for this book can be downloaded from the publisher’s website at www.manning.com/PowerShellandWMI.WARNING All downloaded code must be tested in your environment.
The code is provided as a zip file with a folder for each chapter, except that the nature of chapters 18 and 19 leads to a single folder spanning both of those chapters. A PowerShell file, .ps1, is provided to match each listing in the chapter. The files are named for the listings; for example, Listing3.1.ps1.TIP Each listing is presented as one or more functions. The most efficient way to load these is to use the chapter’s module file.
Other files may be supplied occasionally, such as example output where the data is too big to include on the page or example input files. In all cases, they’re referenced in the chapters.
Alternative coding styles are provided where I have used a report production style of script in the chapter. These can be found in subfolders of the relevant chapter, named “Alternative Non-Report Style”.
In some cases, alternative scripts using the CIM cmdlets from PowerShell v3 are provided as examples of how to use this new functionality. The CIM alternatives are located in a subfolder of the chapter, named “CIM”.
This is a book about using PowerShell, and there are a lot of examples provided throughout the book. A fixed-width font,
this, is used for short lines of code in the text. Listings and longer code examples embedded in the text also use a fixed width font:
Listings are annotated, where necessary, and full explanations are provided in the text. In many cases, the code statements have been split across multiple lines in order to fit the code on the page. These lines either terminate with a back tick (`), which is the PowerShell continuation character, or the following line has a → symbol to indicate that the line is a continuation.
If the code has been typed directly at a PowerShell prompt, it’ll be displayed like this:
I have followed a number of conventions when putting together the code for this book. Some of these are standard PowerShell best practices, and others are my personal coding style. I will usually refer to servers when discussing the types of machines we are administering, but many of the techniques covered in this book can be applied to desktop machines as well.
PowerShell commands (cmdlets and functions) can have shortcut names, known as aliases, defined. I don’t normally use aliases in scripts, because I want to ensure that the scripts are readable, and are as easy to understand as possible. I also use the full parameter names in cmdlets. Cmdlet, parameter, property, and attribute names will be displayed like this.
There is one exception to my rule on aliases, and that’s for the utility cmdlets, where I use the following conventions:
Where-Objectis aliased as
wherebut never as
ForEach-Objectis aliased as
foreachbut never as
Select-Objectis aliased as
Sort-Objectis aliased as
Measure-Object are used less frequently, but they’re aliased to group and
measure respectively. In the discussion around a script, I always use the full cmdlet name. I have adopted this convention for a number of reasons:
I use double quotes around strings unless I am sure that I don’t want to substitute into the string. WMI filters and WQL use single quotes to delineate strings within the query. I also tend to leave keywords, such as
if in lowercase. My function names and their parameters are usually lowercase—I’ll make an exception to this if the name is long and some capitalization makes it more readable.
In some cases, the listings in the book are truncated. This is to save space and is always stated in the script’s discussion. The download code for the book is complete. My goal has been to provide a balance between readability, conciseness, and completeness. Only you can tell if I have succeeded.
Purchase of PowerShell and WMI includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum and subscribe to it, point your web browser to www.manning.com/PowerShellandWMI. This page provides information on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful dialog between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the AO remains voluntary (and unpaid). We suggest you try asking the author some challenging questions, lest his interest stray!
The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.