23,99 €
Prepare for the future of Microsoft automation with this no-nonsense guide Windows PowerShell 2 is the scripting language that enables automation within the Windows operating system. Packed with powerful new features, this latest version is complex, and Windows PowerShell 2 For Dummies is the perfect guide to help system administrators get up to speed. Written by a Microsoft MVP with direct access to the program managers and developers, this book covers every new feature of Windows PowerShell 2 in a friendly, easy-to-follow format. * Windows PowerShell 2 is the updated scripting language that enables system administrators to automate Windows operating systems * System administrators with limited scripting experience will find this book helps them learn the fundamentals of Windows PowerShell 2 quickly and easily * Translates the jargon and complex syntax of Windows PowerShell 2 * Covers script debugging improvements, the ability to invoke commands remotely, and the new user interface * Uses real-world applications to clarify the theory, fundamentals, and techniques of the scripting language * Written by a Microsoft MVP with direct access to the developers of Windows PowerShell 2 Windows PowerShell 2 For Dummies makes this tool easily accessible to administrators of every experience level.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 555
Veröffentlichungsjahr: 2009
Table of Contents
Introduction
About This Book
Conventions Used in This Book
What You’re Not to Read
Foolish Assumptions
How This Book Is Organized
Part I: Getting a Bird’s-Eye View of PowerShell 2
Part II: PowerShell’s Basic Structure and Syntax
Part III: Complex Data Description and Sharing
Part IV: Controlling Where and How You Operate PowerShell
Part V: Real-World Windows Administration Using PowerShell
Part VI: Configuring and Reporting Via PowerShell
Part VII: The Part of Tens
Icons Used in This Book
What’s on the Web Site
Where to Go from Here
Part I: Getting a Bird’s-Eye View of PowerShell 2
Chapter 1: The Windows PowerShell Rap Sheet
Addressing the Need for a Powerful, Windows-Focused Scripting Language
Watching Monad morph into PowerShell
A little bit on Windows PowerShell 1.0
Windows PowerShell 2, the Next Evolution
Installing Windows PowerShell 2
Firing up the Windows PowerShell Command Shell
Going GUI: The Windows PowerShell Integrated Shell Environment (ISE)
Chapter 2: Customizing and Shortcutting the Environment
Personalizing the Look and Feel of the Command Shell
Adding color to your world
Getting size-specific with your windows
A window by any other name . . .
Changing Your PowerShell Profile
Making the Windows PowerShell ISE Work for You
Customizing the ISE
Adding your own functions to the ISE menu
Creating Aliases
Deleting Aliases
Accessing the Alias Drive
Creating Persistent Aliases
Getting to Know Tab Expansion
Chapter 3: A Pinch of Shell, a Pound of Power
Getting a Taste of Windows PowerShell
Creating Your First Script
Breaking Down Your First Script
Sneaking a Peek at Complex Scripts
Examining the Nuts and Bolts of the Complist Script
Part II: PowerShell’s Basic Structure and Syntax
Chapter 4: Shelling Out Commands and Scripts
Cmdlets: The Little Commands That Could!
Putting Cmdlets under a microscope
Checking out existing Cmdlets
Making Cmdlets understand you
One Shell to Rule Them All
Windows Shell scripts
Windows Scripting Host
Chapter 5: When Dollars Turn into Variables
Discovering Variables: They Vary Very Much
Getting to Know Data Types
Dealing with data types
Explicitly defining the data type
Casting values
Constant and Read-Only Variables
Understanding Automatic Variables
Working with Objects through Variables
Chapter 6: A Bit of Logic to Save the Day
A Logic Primer
Branching Using If/Else
Using the Switch Statement
Doing It Over and Over and Over Again with Loops
Looping with For
Using Foreach to loop through collections
Looping for a While
Running a loop at least once with Do While
Taking a look at Do Until
Avoiding loop pitfalls
Chapter 7: Working on a Pipeline
Using Pipelines to Streamline Your Commands
Stringing Commands Together
Getting the Right Output
Part III: Complex Data Description and Sharing
Chapter 8: Working with Windows Management Instrumentation
Getting Familiar with Windows Management Instrumentation
Examining the WMI architecture
Poking around in WMI namespaces
Securing WMI
Making Windows PowerShell Interact with WMI
Using SQL Syntax in WMI to Get WQL
Harnessing the Power of WMI
Querying service status
Looking for event log entries
Changing WMI Authentication Levels
Pretending to Be Someone Else Using Impersonation
Using the New WMI Cmdlets
Making things happen with Invoke-WMIMethod
Deleting objects using Remove-WmiObject
Setting WMI properties using Set-WmiInstance
Chapter 9: Bringing Strings into the Limelight
Taking Your First Look at Strings
Differentiating between empty and null strings
Creating literal strings
Simplifying using Here-Strings
Performing String Surgery
Combining strings
Combining strings with nonstrings
Splitting strings
Snipping off a piece of a string
Performing string substitutions
Working with String Positions
Changing the Case of Strings
Using Regular Expressions
Creating the simplest RegEx using literal characters
Performing more dynamic searches using character sets
Using modifiers to define optional or repeating sequences
Using anchors to maintain position
Coming up with alternatives
Making use of RegEx in Windows PowerShell
Chapter 10: I’ll Take Numbers for $100, Please
Putting Numeric Data Types under a Microscope
Having a look at integral data types
Getting precise using nonintegral data types
Doing Some Calculations
Adding things up
Reducing values with subtraction
Expanding through multiplication
Reducing through division
Rounding Off Values
Creating Random Numbers
Converting Numbers
Watching Out for Overflow
Chapter 11: Grouping Data Using Arrays and Hash Tables
Taking an In-Depth Look at Arrays
Creating and Using Arrays
Accessing array elements
Looping through arrays
Growing Arrays Dynamically
Creating Multidimensional Arrays
Finding Other Uses for Arrays
Working with Hash Tables: The Array’s Useful Cousin
Creating and using hash tables
Modifying hash tables
Looping through hash tables
Chapter 12: Readin’ and Writin’ Files
Having Some Fun with the File System
Moving around the file system
Managing directories
Manipulating files in the file system
Reading Text Files
Writing Files
Working with XML
Reading and writing XML files
Saving objects in XML files
Working with HTML
Chapter 13: Going On a Date with PowerShell
Going On Your First Date
Getting the date and time in a specific format
Creating your own dates
Using Date Math (It’s Not Just for Nerds)
Calculating time differences
Looking into the future
Checking whether it’s daylight saving time
Dealing with Time Zones
Standardizing with Coordinated Universal Time
Using the TimeZone class
Part IV: Controlling Where and How You Operate PowerShell
Chapter 14: Using Functions to Divide and Conquer
Reusing Code Using Functions
Creating your first function
Defining parameters
Returning values
Using Scope
Understanding scope rules
Watching out for name overlap
Defining functions in Global scope
Creating Your Own Cmdlets — Advanced Functions!
Understanding the structure of Advanced Functions
Defining attributes
Defining parameters
Using methods
Running Advanced Functions
Finding uses for Advanced Functions
Chapter 15: PowerShell Ninjas: Running Jobs Remotely or in the Background
Using Background Jobs
Enabling WinRM
Starting a new job
Getting results
Waiting for a job
Terminating a job
Bringing a job to a grinding halt
Running Commands Remotely
Using Windows PowerShell everywhere
Getting what you need for remote commands
Speaking PowerShell with a different computer
Invoking commands remotely
Creating a persistent connection
Running remote background jobs
Understanding policies, profiles, and precedence
Chapter 16: Making Your Script Speak Different Languages
Seeing the Importance of Internationalizing Scripts
Giving Your Scripts Different Tongues
Using new internationalization features
Understanding cultures
Putting it all together
Sharing Scripts with Others
Chapter 17: Smashing Those Bugs
Finding Out Where the Bugs Come From
Guarding against unexpected input
Watching out for incorrect logic
Expecting the unexpected: System errors
Understanding the Debugging Process
Working On Your Defense
Working with Debugging Tools
Working with breakpoints
Setting fancier breakpoints
Issuing debugger commands
Listing all breakpoints
Disabling and enabling breakpoints
Removing breakpoints
Part V: Real-World Windows Administration Using PowerShell
Chapter 18: Mission Control: All Systems Go
Monitoring Drive Space
Converting to Windows Management Infrastructure from System.IO.DriveInfo
Managing Windows Services
Controlling services
Configuring services
Checking Your Event Logs
Querying EventLogs Using WMI
Chapter 19: Taming the Windows Registry
Following the Registry Tree
Connecting to the Windows Registry
Navigating the registry by using the PowerShell drives
Using Microsoft.Win32.RegistryKey to access the registry
Reading Keys and Values
Writing Keys and Values
Writing keys and values using the PSDrive
Writing registry values using Microsoft.Win32.RegistryKey
Renaming and Deleting Registry Keys and Values
Renaming and deleting registry keys and Values using PSDrive
Using Microsoft.Win32.RegistryKey to delete registry keys and values
Chapter 20: Reaching Out to Active Directory
A Really Brief Active Directory Primer
Connecting to Active Directory
Querying for Objects and Attributes
Creating your LDAP filter
Dynamically obtaining a user’s distinguishedName
Modifying Object Attributes
Updating Group Membership
Getting to the Raw ADSI Object Using psbase
Chapter 21: PowerShell Lockdown
PowerShell Security Features
Getting rid of the current directory loophole
Stopping the double-click blues
Protecting through ExecutionPolicy
Generating a Code-Signing Certificate
Creating a self-signed certificate
Requesting a certificate from your Enterprise CA
Browsing the Certificate Store
Signing Your Scripts
Managing the Windows Firewall
Defining globally open ports
Listing firewall services
Allowing applications to get through
Chapter 22: Converting Your Old Scripts: Out with the Old, In with the New
Converting a Windows Shell Script to Windows PowerShell
Echoing to the screen
Using conditional statements
Migrating that FOR command
Converting a Windows Scripting Host Script to Windows PowerShell
Comparing the basics
Working with COM objects
Understanding the difference between CreateObject and GetObject
Handling I/O
Working with ActiveX Data Objects (ADO)
Leveraging ADO.NET to your advantage
Part VI: Configuring and Reporting Via PowerShell
Chapter 23: Controlling Your Network Configuration
Managing Your Network Settings
Familiarizing yourself with Win32_NetworkAdapterConfiguration
Retrieving your TCP/IP settings
Manipulating your TCP/IP settings
Managing Your Windows Firewall
Getting to know the Windows Firewall COMmander
Enabling and disabling the Windows Firewall
Making yourself visible
Getting a list of all authorized applications
Getting a list of all globally open ports
Using the big reset button
Chapter 24: Managing Your Hardware
Polling Your Hardware
Finding out what hardware you have
Checking hardware state
Controlling Your Printers
Connecting to a shared network printer
Disconnecting a shared network printer
Setting the default printer
Checking up on printer state
Keeping an eye on the printer queue
Chapter 25: Making Reporting Easy
Using Built-In Reporting Cmdlets
Generating Reports
Customizing tabular output with Format-Table
Setting column width in Format-Table
Using an interactive data table
Preparing data for other reporting tools
Making your data table ready
Making Reports Pretty
Formatting Using Cascading Style Sheets
Using Third-Party Reporting Tools
Part VII: The Part of Tens
Chapter 26: The Ten Most Important Cmdlets
Getting Help with Get-Help
Getting to Know Your Objects with Get-Member
Navigating with Set-Location
Reading Text Files with Get-Content
Writing to a File with Out-File
Leveraging WMI with Get-WMIObject
Creating New Objects with New-Object
Getting Picky with Select-Object
Going Through Collections with Foreach-Object
Controlling the Pipeline with Where-Object
Chapter 27: Ten Common PowerShell Mistakes
Forgetting to Change the Execution Policy
Using Commas to Separate Parameters When Calling a Function
Defining Functions After You Use Them
Treating Pipeline Data as Strings
Forgetting to Cast Variables as a String
Using Incorrect Comparison Operators
Trying to Do Too Much in One Pipeline
Forgetting About Variable Scope
Not Using the Debugger
Not Using .NET Classes When Available
Windows PowerShell™ 2 For Dummies®
by Steve Seguis
Windows PowerShell™ 2 For Dummies®
Published byWiley Publishing, Inc.111 River St.Hoboken, NJ 07030-5774www.wiley.com
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Library of Congress Control Number:
ISBN: 978-0-470-37198-5
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
About the Author
Steve Seguis lives with his amazing wife, Annalene, in New York City, New York. He is a twelve-year Windows Systems Engineer veteran and specializes in systems automation. He was a Microsoft Most Valuable Professional (MVP) for Windows Server — Admin Framework from 2004–2007. He is also a contributing writer and technical editor for Windows IT Pro and, most recently, has published a book on Windows Server 2008 Administration.
Dedication
To my parents, Romeo and Lourdes, who gave me the opportunities that have allowed me to pursue my dreams and become who I am today.
Author’s Acknowledgments
I’ve always been a fan of the For Dummies books, which has often resulted in one or two chuckles from my colleagues due to the incorrect perception that somehow reading a For Dummies book implies a lack of intelligence. The reality is that I’m a fan of making complex things simple and I like books that focus on getting me the information I need in an easy, digestible format. The For Dummies books have been doing this for years, and ever since I read my first For Dummies book (specifically C For Dummies by Dan Gookin, over a dozen years ago), I was captured by the ease at which I was able to gain knowledge while having the occasional laugh. I never in my wildest imagination thought I’d ever have the opportunity to write one myself . . . that is until my agent, David Fugate, got me in touch with the good people over at Wiley Publishing and got this journey started. Thanks David!
I’d like to thank Greg Croy, Executive Editor, for getting my proposal for this book approved. He actually retired before I was done writing the book, but kudos to him for getting the ball rolling. Thanks goes out to Blair Pottenger, Project Editor, for keeping me well-informed, answering all my questions, and putting in a lot of work to get the book finished. Of course, I’d also like to thank Katie Mohr, Acquisitions Editor, who took over Greg’s role in this project after he retired. Katie went on maternity leave just before we got done with the book, so congratulations Katie on the new baby. The project had hit a bit of a plateau half way through, but when she took over we were able to regroup and get everything back on track.
I have to thank my very patient and supportive wife, Annalene, who puts up with me disappearing into the cubby hole I call my home office for late night writing sessions and generally dealing with all my quirks. We somehow work together to stay sane despite our lives going at 100 miles an hour.
I also have to thank my parents and my family for understanding how busy I get, generally staying out of my hair (what hair I have left), and letting me pursue my interests even though they continue to say that I need to slow down a bit and get some more sleep.
Finally, I’d like to thank the guys over at Microsoft for creating this awesome scripting language called Windows PowerShell. We’ve come a long way since batch files and as a long-time Windows administrator, I bow to your greatness. Windows PowerShell is truly empowering and more Windows folks in every company need to embrace it.
Publisher’s Acknowledgments
We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/.
Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and Media Development
Project Editor: Blair J. Pottenger
Executive Editor: Greg Croy
Acquisitions Editor: Katie Mohr
Copy Editors: Virginia Sanders, Kathy Simpson
Technical Editor: David Dalan
Editorial Manager: Kevin Kirschner
Media Development Project Manager: Laura Moss-Hollister
Media Development Assistant Project Manager: Jenny Swisher
Media Development Associate Producer: Josh Frank
Sr. Editorial Assistant: Cherie Case
Cartoons: Rich Tennant (www.the5thwave.com)
Composition Services
Project Coordinator: Lynsey Stanford
Layout and Graphics: Melanee Habig, Melissa K. Jester
Proofreaders: Melissa Cossell, Christopher M. Jones
Indexer: Potomac Indexing, LLC
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Composition Services
Debbie Stailey, Director of Composition Services
Part I
Getting a Bird’s-Eye View of PowerShell 2
In this part . . .
It’s hard to really understand something without putting it in context. These first three chapters paint the scene for the rest of the book and give you a taste of what Windows PowerShell 2 is like. I like to think of this part as a quick tour of Windows PowerShell, past and present, so that you not only understand why Windows PowerShell is the way it is but also to demonstrate some of the things you can accomplish with it that I hope will create a thirst for more.
Chapter 1 helps you get your arms around Windows PowerShell by giving you an understanding of how it got where it is today. I show you how to customize the environment to best fit your style and some different time-saving techniques that help get you going faster in Chapter 2. Finally, Chapter 3 gives you your first taste of this amazing shell.
Chapter 1
The Windows PowerShell Rap Sheet
In This Chapter
Following the birth and evolution of Windows PowerShell
Installing Windows PowerShell 2
Interacting with the Windows PowerShell command shell
Using the Integrated Scripting Environment (ISE)
I’m a really lazy person by nature. I’m not lazy in the sense that I like to sit down and do nothing all day long, but rather I hate doing things over and over again. Whenever I find myself doing something very mundane, the first thing that pops into mind is “there has to be a way to automate this!” Computers are great work horses. They can run day in and day out and never complain. Logically, it makes sense to make your computer work for you rather than the other way around, so in my infinite laziness I’m constantly cooking up ways to make my computer work harder so I can have time to do more important things . . . like write this book for you.
Whether you’re completely new to scripting or have done some level of automation in the past using other scripting languages, you’ll really love Windows PowerShell. It gives Windows users a true shell that provides the same power over the Windows system that only people in the Unix/Linux community enjoyed previously. Microsoft has spent years and years trying to make Windows easier to use, and in the process of doing so have made some things quite frustrating for power users. (Remember when Microsoft was trying to force you to use wizards only?) Windows PowerShell is, in my mind, Microsoft’s way of acknowledging that a significant number of users know what they want and don’t want to sit around all day long clicking through dialog boxes to get their jobs done.
Addressing the Need for a Powerful, Windows-Focused Scripting Language
You’ve always had the standard Windows Shell, also known as the command shell or the DOS prompt (for those who can’t let go of the past), to interact with Windows at the command line. You can automate various aspects of Windows from the command shell using built-in commands, other command line applications, and even string them together into Windows Shell scripts (or batch files for those still clamoring for the good old DOS days). If you want a bit more power and control, you can use Windows Scripting Host (WSH) and then use VBScript or JScript to automate your tasks. So the obvious question is “why add Windows PowerShell to this mix?” After all, can’t you accomplish everything you need to do using these existing methods?
Sure, a good portion of everything you need to do in Windows can be accomplished by writing a Windows Shell or WSH script. I’ve been doing it for years with no problems, and when I first heard of Windows PowerShell being developed several years ago (when it was still under the codename Monad) I had mixed feelings. On one hand, it promised a whole new way of doing things, which was exciting, but on the other hand it just became one more thing I needed to learn. As Windows PowerShell came into maturity, I clearly saw that it really did live up to its promises, and I found myself jumping on the Windows PowerShell bandwagon.
Watching Monad morph into PowerShell
Windows PowerShell was architected by Jeffrey P. Snover back in August 2002, under the codename Monad. According to the original Monad Manifesto, it was designed as the next-generation platform for administrative automation. It was based loosely on the tried and proven approach for administrative automation in Unix.
In traditional command shells, you achieve a desired action by manipulating generally unstructured text output of a previous command to generate the desired output or effect using another command. In a regular Windows Command Shell, for example, you can use the following command sequence to find out if pinging www.whitehouse.gov returns any replies.
ping www.whitehouse.gov | find “Reply”
In the example, you pass the output of the ping command against www.whitehouse.gov into the find command because you want to filter the output so only the lines containing the word Reply get displayed. Monad tackled the limitations of this traditional method by devising a new approach for building commands by leveraging the .NET framework and its object model. Monad does this by defining an automation model where commands called Cmdlets (read as command-lets) can pass data to each other as structured objects rather than a loose collection of text.
My intent isn’t to give you a history lesson on Windows PowerShell but rather to help you understand why it looks and acts the way it does. As you use Windows PowerShell, you might notice, for example, that the command syntax has a Unix feel to it. This isn’t by coincidence but rather due to the language being modeled from powerful Unix shells with the added .NET twist. Don’t be intimated, however — PowerShell is one of the easiest scripting languages to use and is very intuitive.
If you want to read the Monad Manifesto as it originally appeared in 2002, you can view it on the Windows PowerShell team blog (http://blogs.msdn.com/powershell/archive/2007/03/19/monad-manifesto-the-origin-of-windows-powershell.aspx).
A little bit on Windows PowerShell 1.0
Windows PowerShell brings together the best parts of interacting with the traditional Windows Shell along with the power of writing WSH scripts. It creates a rich command line–based environment that puts more power into your hands by letting you run new PowerShell commands called Cmdlets. These are .NET class–based commands that give you the flexibility of high-level scripting while allowing you to access very low-level Application Programming Interfaces (APIs) through .NET wrappers.
Windows PowerShell 1.0 was the first full-production release of Windows PowerShell, and even though it delivered on many of the key elements needed to use it, it was adopted slowly for a few reasons:
It wasn’t built into any of the existing Windows operating systems, so administrators who wanted to use it had to make a conscious effort to deploy the PowerShell run-time.
Administrators who had already mastered existing scripting languages didn’t feel the need to use a new shell to accomplish the same tasks.
As a new product, it took a while for enough people to start using it before the Windows PowerShell community became proficient enough to be able to demonstrate the more creative ways to use it.
Eventually Microsoft’s own developers started taking advantage of Windows PowerShell 1.0, and it was soon adopted in their mainstream products like Microsoft Exchange 2007 and Systems Center Operations Manager (SCOM, formerly known as MOM). PowerShell 1.0 was then released with Windows Server 2008 as an installable, out-of-box feature. You and I should be excited about this because it really brings Windows PowerShell into the mainstream and also demonstrates Microsoft’s commitment to bringing Windows PowerShell into the forefront of its systems management strategies.
Windows PowerShell 2, the Next Evolution
Despite the slow adoption of Windows PowerShell 1.0, a growing Windows PowerShell community emerged and put it through its paces. The Windows PowerShell developers at Microsoft took a lot of this feedback and criticism to produce what promises to be a much more production-worthy scripting environment — Windows PowerShell 2.
I’m sure enough time has now elapsed since you first heard about Windows PowerShell that it has piqued your curiosity (which is probably one of the reasons why you picked up this book). It’s a great time for you to discover this scripting language because many of the limitations people faced while working with Windows PowerShell 1.0 have since been worked out. What you’re all left with is a much more usable command shell that offers a host of different ways to do things. Your only real limit is your own creativity.
I know you’re already asking the obvious: What’s new in Windows PowerShell 2 that makes it so special? Here are some of the major changes and enhancements made to Windows PowerShell:
PowerShell remoting: Gives you the ability to execute Cmdlets and scripts remotely. See Chapter 15.
Background jobs: As the name implies, this improvement allows you to run commands in the background while you continue to work on other things. See Chapter 15.
Advanced functions: Cmdlets used to be written only in C# and VB.NET. Now you can write your command pseudo-Cmdlets using Windows PowerShell itself. See Chapter 14.
Data language: Gives you the ability to separate your code from the data, making it more portable and easier to share.
Script internationalization: Helps scripts that have to accommodate multiple languages easier to implement. See Chapter 16.
Script debugging: Finally, real debugging. You can set breakpoints in your scripts so you can halt execution to find out what’s going on at a particular point in the script. See Chapter 17.
Some new operators and automatic variables: Some new operators to make it easier to split and join strings and automatic variables for accessing user interface language information. See Chapter 5.
Additional new Cmdlets: Mostly to support the preceding features.
Constrained runspaces: Gives you the ability to constrain what commands and scripts Windows PowerShell can run within a given runspace.
Runspace pools: You can think of these as ways to manage command execution by pooling together runspaces.
Integrated Scripting Environment (ISE): A graphical version of the command shell that adds some cool new features such as multi-tabbed panes for working with multiple scripts at the same time. See Chapter 2.
Out-GridView: You can output the results of your commands in an interactive table where you can then sort, search, and group the results. See Chapter 25.
New PowerShell APIs: If you’re a programmer, you can get to the new features provided in PowerShell directly using these APIs.
Some minor enhancements to existing commands and shell behavior: Some additional parameters to existing commands have been added to increase functionality.
Even if you haven’t used Windows PowerShell in the past, you can tell just by this list of new features that there are some significant enhancements to Windows PowerShell that go beyond the surface. I think Windows PowerShell 2 is a more complete product that still makes it easy for new users like you to master it while leaving plenty of room for you to grow.
What’s really amazing is that while I’d classify many of the changes in Windows PowerShell 2 under an advanced feature category, discovering how to use them is a quick and easy thing even for a beginner. Before you know it, and with the help of this really cool book you’re reading, you too will be taking advantage of these new features.
Installing Windows PowerShell 2
Words are just words. I know your heart is pumping already and you’re about to scream at the top of your lungs “I want to use Windows PowerShell already, stop talking and tell me how!” Because Windows PowerShell 2 doesn’t ship with any of the Windows operating systems except Windows 7, you’ll generally need to install it first. Luckily, this task is relatively pain-free, so stick with me for a few seconds.
Windows PowerShell 2 is a replacement for Windows PowerShell 1.0. They can’t co-exist on the same system, so if you already have Windows PowerShell 1.0 installed, make sure you uninstall it first. Note: To uninstall Windows PowerShell 1.0, you might have to select the Show Updates option in the Add/Remove Programs control panel applet for it to be visible.
Windows PowerShell 2 can be installed on both the x86 and x64 platforms of Windows XP with SP3, Windows Server 2003 with SP2, Windows Vista with SP1, Windows Server 2008, and Windows 7.
You install Windows PowerShell 2 using these four simple steps:
1. Download and install Microsoft .NET Framework 2.0
2. Download and install Microsoft .NET Framework 3.5.1.
Required for Windows PowerShell Integrated Scripting Environment (ISE) and Out-GridView.
3. Download and install WinRM 2.0 CTP3.
This is required if you want to take advantage of the remoting and background jobs features.
4. Download and install Windows PowerShell 2.
I’m not going to give you step-by-step instructions here because it’s a straightforward “next, next, next” installation.
Firing up the Windows PowerShell Command Shell
Congratulations! Now that you’ve got Windows PowerShell 2 installed, you can finally have some fun.
First, going forward, you might see me referring to Windows PowerShell 2 simply as PSH. Not only will this save me from carpal tunnel syndrome, but Windows PowerShell is often referred to as PSH within Windows PowerShell community, so don’t be surprised if you see that abbreviation. (It’s also sometimes just called PS.)
Fire up the PSH command shell by choosing Start⇒All Programs⇒Windows PowerShell V2⇒Windows PowerShell V2.
If you’re running Windows Vista, you may need to right-click the shortcut and choose the option to run as Administrator (running elevated) even if you have administrative rights on the system if you get access denied errors.
Windows PowerShell 2 launches and the command shell opens, as shown in Figure 1-1. It looks a lot like your old Windows command shell, except that by default the background is blue and the prompt is prefixed by PS. You can run some familiar DOS commands (such as DIR and CD), and they’ll still work, but the output might look a bit different. Also, running some existing command line applications like XCOPY.EXE works too! I get into how this all works in future chapters, but the ability to run non-PowerShell commands is one of the greatest things about PSH — you can start using PSH today as a replacement command shell and run your old commands while getting familiar with the new PSH way.
PSH runs your regular command line applications as normal, but the built-in commands such as CD and DIR are actually aliases to new PSH Cmdlets. This is why the output of DIR looks a bit different. Also notice that you can’t use the old switches (such as DIR /W) with DIR. The reason is because the underlying Cmdlet that DIR is mapped to uses different parameters. I talk more about aliases in Chapter 2.
Figure 1-1: The Windows PowerShell command shell.
Going GUI: The Windows PowerShell Integrated Shell Environment (ISE)
The Windows PowerShell Integrated Shell Environment (ISE) is a bit of a mouthful, but it’s really just a more graphically rich interface (see Figure 1-2) for interacting with PSH. You launch it the same way as the regular PSH command shell (see the preceding section), but you select Windows PowerShell ISE instead; select Start⇒All Programs⇒Windows PowerShell v2⇒Windows PowerShell ISE.
Figure 1-2: Txhe Windows PowerShell ISE.
Here’s what you get with this handsome interface:
Script/Editor pane: This is where you can view and edit your PSH scripts.
Output pane: This is where the output of all your command or script is displayed.
Command pane: You can enter commands in this pane just as you would in a regular PSH command shell.
You can also create PSH scripts by choosing File⇒New to display the editor pane above the output pane. If you’re working on multiple scripts, a tabbed interface is displayed so you can easily switch back and forth between the different script windows, as shown in Figure 1-3.
Figure 1-3: The Windows PowerShell ISE window with the tabbed script editor interface.
You’ll also notice that when you have a script open, you can run it simply by clicking the Run button (the right-pointing triangle, similar to the Play button on a CD player) on the toolbar. The toolbar has all the standard text-editing features as well as syntax highlighting, which makes editing your scripts a bit easier on the eyes. The best part is that the debugger is easily accessible from the Debug menu. (I cover debugging concepts in-depth in Chapter 17.) The ISE is an excellent tool for writing, running, and debugging your scripts in one easy-to-use environment. Think of it as a miniature Visual Studio for Windows PowerShell. I talk more about the ISE in the next chapter.
Although the ISE script pane is primarily designed for writing and editing scripts, it’s a pure text editor, so you can use it to open or create plain text files and XML files.
