win power shell

Download Win Power Shell

If you can't read please download the document

Upload: som-chakre

Post on 25-Oct-2014

45 views

Category:

Documents


0 download

TRANSCRIPT

Windows PowerShell PrimerMicrosoft Corporation Published: September 2006

AbstractWindows PowerShell is a new Windows command-line shell designed especially for system administrators. The shell includes an interactive prompt and a scripting environment that can be used independently or in combination. This document describes the basic concepts and features of Windows PowerShell and suggests ways that you can use Windows PowerShell in system administration.

2

ContentsWindows PowerShell Primer Copyright................................................................................................ Windows PowerShell Introduction........................................................................................................

Audience........................................................................................................................... About Windows PowerShell.................................................................................................. Discoverability................................................................................................................... Consistency...................................................................................................................... Interactive and Scripting Environments............................................................................. Object Orientation............................................................................................................. Easy Transition to Scripting............................................................................................... Installing and Running Windows PowerShell........................................................................ Installation Requirements.................................................................................................. Installing Windows PowerShell.......................................................................................... Running Windows PowerShell........................................................................................... Windows PowerShell Basics................................................................................................. Understanding Important Windows PowerShell Concepts..................................................... Commands are not Text-based...................................................................................... The Command Family is Extensible............................................................................... Windows PowerShell Handles Console Input and Display.............................................. Windows PowerShell Uses Some C# Syntax................................................................. Learning Windows PowerShell Names................................................................................. Cmdlets Use Verb-Noun Names to Reduce Command Memorization............................ Cmdlets Use Standard Parameters................................................................................ The Help Parameter (?).............................................................................................. Common Parameters................................................................................................. Suggested Parameters............................................................................................... Getting Summary Command Information.............................................................................. Displaying available command types............................................................................. Getting Detailed Help Information......................................................................................... Using Familiar Command Names......................................................................................... Interpreting Standard Aliases......................................................................................... 2

Creating New Aliases..................................................................................................... Using Tab Expansion to Automatically Complete Names...................................................... Object Pipeline..................................................................................................................... Understanding the Windows PowerShell Pipeline................................................................. Viewing Object Structure (Get-Member)............................................................................... Using Format Commands to Change Output View................................................................ Using Format-Wide for Single-Item Output..................................................................... Controlling Format-Wide Display with Column............................................................ Using Format-List for a List View.................................................................................... Getting Detailed Information by using Format-List with Wildcards............................... Using Format-Table for Tabular Output........................................................................... Improving Format-Table Output (AutoSize)................................................................. Wrapping Format-Table Output in Columns (Wrap)..................................................... Organizing Table Output (-GroupBy)........................................................................... Redirecting Data with Out-* Cmdlets..................................................................................... Paging Console Output (Out-Host)............................................................................. Discarding Output (Out-Null)....................................................................................... Printing Data (Out-Printer).......................................................................................... Saving Data (Out-File)................................................................................................ Windows PowerShell Navigation.......................................................................................... Managing the Current Location in Windows Powershell........................................................ Getting Your Current Location (Get-Location)................................................................. Setting Your Current Location (Set-Location)................................................................. Saving and Recalling Recent Locations (Push-Location and Pop-Location)................... Managing Windows PowerShell Drives................................................................................. Adding New Windows PowerShell Drives (New-PSDrive).............................................. Deleting Windows PowerShell Drives (Remove-PSDrive).............................................. Adding and Removing Drives Outside Windows PowerShell.......................................... Working With Files, Folders and Registry Keys..................................................................... Enumerating Files, Folders, and Registry Keys (Get-ChildItem)..................................... Listing all Contained Items (-Recurse)........................................................................ Filtering Items by Name (-Name)................................................................................ Forcibly Listing Hidden Items (-Force)........................................................................ Matching Item Names with Wildcards.........................................................................

4 Excluding Items (-Exclude)......................................................................................... Mixing Get-ChildItem Parameters............................................................................... Manipulating Items Directly................................................................................................... Creating New Items (New-Item)..................................................................................... Why Registry Values are not Items................................................................................ Renaming Existing Items (Rename-Item)....................................................................... Moving Items (Move-Item)............................................................................................. Copying Items (Copy-Item)............................................................................................ Deleting Items (Remove-Item)....................................................................................... Executing Items (Invoke-Item)........................................................................................ Working with Objects............................................................................................................ Getting WMI Objects (Get-WmiObject)................................................................................. Getting WMI Objects (Get-WmiObject).............................................................................. Listing WMI Classes...................................................................................................... Displaying WMI Class Details........................................................................................ Displaying Non-Default Properties with Format Cmdlets............................................. Creating .NET and COM Objects (New-Object).................................................................... Using New-Object for Event Log Access........................................................................ Using Constructors with New-Object.......................................................................... Storing Objects in Variables........................................................................................ Accessing a Remote Event Log with New-Object....................................................... Clearing an Event Log with Object Methods............................................................... Creating COM Objects with New-Object........................................................................ Creating a Desktop Shortcut with WScript.Shell............................................................. Using Internet Explorer from Windows PowerShell........................................................ Getting Warnings about .NET-Wrapped COM Objects................................................... Using Static Classes and Methods....................................................................................... Getting Environment Data with System.Environment..................................................... Referring to the Static System.Environment Class...................................................... Displaying Static Properties of System.Environment................................................... Doing Math with System.Math........................................................................................ Removing Objects from the Pipeline (Where-Object)............................................................ Performing Simple Tests with Where-Object.................................................................. Filtering Based on Object Properties.............................................................................. Repeating a Task for Multiple Objects (ForEach-Object)....................................................... Selecting Parts of Objects (Select-Object)............................................................................ 4

Sorting Objects..................................................................................................................... Using Variables to Store Objects.......................................................................................... Creating a Variable........................................................................................................ Manipulating Variables................................................................................................... Using Cmd.exe Variables............................................................................................... Using Windows PowerShell for Administration...................................................................... Managing Local Processes................................................................................................... Listing Processes (Get-Process).................................................................................... Stopping Processes (Stop-Process)............................................................................... Stopping All Other Windows PowerShell Sessions......................................................... Managing Local Services...................................................................................................... Listing Services.............................................................................................................. Stopping, Starting, Suspending, and Restarting Services............................................... Collecting Information About Computers............................................................................... Listing Desktop Settings................................................................................................. Listing BIOS Information................................................................................................ Listing Processor Information......................................................................................... Listing Computer Manufacturer and Model..................................................................... Listing Installed Hotfixes................................................................................................ Listing Operating System Version Information................................................................ Listing Local Users and Owner...................................................................................... Getting Available Disk Space......................................................................................... Getting Logon Session Information................................................................................ Getting the User Logged on to a Computer.................................................................... Getting Local Time from a Computer.............................................................................. Displaying Service Status.............................................................................................. Working with Software Installations....................................................................................... Listing Windows Installer Applications............................................................................ Listing All Uninstallable Applications............................................................................... Installing Applications..................................................................................................... Removing Applications................................................................................................... Upgrading Windows Installer Applications...................................................................... Changing Computer State: Locking, Logging Off, Shutting Down, and Rebooting................. Locking a Computer....................................................................................................... Logging Off the Current Session.................................................................................... Shutting Down or Rebooting a Computer.......................................................................

6 Working with Printers............................................................................................................ Listing Printer Connections............................................................................................ Adding a Network Printer............................................................................................... Setting a Default Printer................................................................................................. Removing a Printer Connection..................................................................................... Performing Networking Tasks............................................................................................... Listing IP Addresses for a Computer.............................................................................. Listing IP Configuration Data.......................................................................................... Pinging Computers........................................................................................................ Retrieving Network Adapter Properties........................................................................... Assigning the DNS Domain for a Network Adapter......................................................... Performing DHCP Configuration Tasks.......................................................................... Determining DHCP-Enabled Adapters........................................................................ Retrieving DHCP Properties....................................................................................... Enabling DHCP on Each Adapter............................................................................... Releasing and Renewing DHCP Leases on Specific Adapters.................................... Releasing and Renewing DHCP Leases on All Adapters............................................ Creating a Network Share.............................................................................................. Removing a Network Share........................................................................................... Connecting a Windows Accessible Network Drive.......................................................... Working with Files and Folders............................................................................................. Listing All the Files and Folders Within a Folder............................................................. Copying Files and Folders............................................................................................. Creating Files and Folders............................................................................................. Removing All Files and Folders Within a Folder............................................................. Mapping a Local Folder as a Windows Accessible Drive................................................ Reading a Text File into an Array.................................................................................... Working with Registry Keys.................................................................................................. Listing All Subkeys of a Registry Key............................................................................. Copying Keys................................................................................................................ Creating Keys................................................................................................................ Deleting Keys................................................................................................................ Removing All Keys Under a Specific Key....................................................................... Working with Registry Entries............................................................................................... Listing Registry Entries.................................................................................................. Getting a Single Registry Entry...................................................................................... Creating New Registry Entries....................................................................................... Renaming Registry Entries............................................................................................ 6

Deleting Registry Entries................................................................................................ Appendix 1 - Compatibility Aliases........................................................................................ Appendix 2 - Creating a Custom PowerShell Shortcut..........................................................

Windows PowerShell Primer CopyrightThis document is provided for informational purposes only and Microsoft makes no warranties, either express or implied, in this document. Information in this document, including URL and other Internet Web site references, is subject to change without notice. The entire risk of the use or the results from the use of this document remains with the user. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft; the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2006 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, Windows 2000, Windows XP, and Windows Server 2003, are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Windows PowerShell IntroductionWindows PowerShell is a command-line shell and scripting environment that brings the power of the .NET Framework to command-line users and script writers. It introduces a number of powerful new concepts that enables you to extend the knowledge you have gained and the scripts you have created within the Windows Command Prompt and Windows Script Host environments.

9

AudienceThe Windows PowerShell Primer is intended for IT professionals, programmers, and power users who have no prior background with Windows PowerShell. Although a background in scripting and WMI are helpful, they are not assumed or required to understand this document.

About Windows PowerShellWindows PowerShell is designed to improve the command-line and scripting environment by eliminating long-standing problems and adding new features.

DiscoverabilityWindows Powershell makes it easy to discover its features. For example, to find a list of cmdlets that view and change Windows services, type:get-command *-service

After discovering which cmdlet accomplishes a task, you can learn more about the cmdlet by using the Get-Help cmdlet. For example, to display help about the Get-Service cmdlet, type:get-help get-service

To fully understand the output of that cmdlet, pipe its output to the Get-Member cmdlet. For example, the following command displays information about the members of the object output by the Get-Service cmdlet.get-service | get-member

ConsistencyManaging systems can be a complex endeavor and tools that have a consistent interface help to control the inherent complexity. Unfortunately, neither command-line tools nor scriptable COM objects have been known for their consistency. The consistency of Windows PowerShell is one of its primary assets. For example, if you learn how to use the Sort-Object cmdlet, you can use that knowledge to sort the output of any cmdlet. You do not have to learn the different sorting routines of each cmdlet.

In addition, cmdlet developers do not have to design sorting features for their cmdlets. Windows PowerShell gives them a framework that provides the basic features and forces them to be consistent about many aspects of the interface. The framework eliminates some of the choices that are typically left to the developer, but, in return, it makes the development of robust and easy-to-use cmdlets much simpler.

Interactive and Scripting EnvironmentsWindows PowerShell is a combined interactive and scripting environment that gives you access to command-line tools and COM objects, and also enables you to use the power of the .NET Framework Class Library (FCL). This environment improves upon the Windows Command Prompt, which provides an interactive environment with multiple command-line tools. It also improves upon Windows Script Host (WSH) scripts, which let you use multiple command-line tools and COM automation objects, but do not provide an interactive environment. By combining access to all of these features, Windows PowerShell extends the ability of the interactive user and the script writer, and makes system administration more manageable.

Object OrientationAlthough you interact with Windows PowerShell by typing commands in text, Windows PowerShell is based on objects, not text. The output of a command is an object. You can send the output object to another command as its input. As a result, Windows PowerShell provides a familiar interface to people experienced with other shells, while introducing a new and powerful command-line paradigm. It extends the concept of sending data between commands by enabling you to send objects, rather than text.

Easy Transition to ScriptingWindows PowerShell makes it easy to transition from typing commands interactively to creating and running scripts. You can type commands at the Windows PowerShell command prompt to discover the commands that perform a task. Then, you can save those commands in a transcript or a history before copying them to a file for use as a script.

11

Installing and Running Windows PowerShellInstallation RequirementsBefore you install Windows PowerShell, be sure that your system has the software programs that Windows PowerShell requires. Windows PowerShell requires the following programs: Windows XP Service Pack 2, Windows 2003 Service Pack 1, or later versions of Windows Microsoft .NET Framework 2.0

If any version of Windows PowerShell is already installed on the computer, use Add or Remove Programs in Control Panel to uninstall it before installing a new version.

Installing Windows PowerShellTo install Windows PowerShell: 1. Download the Windows PowerShell installation file. (The name of the file will differ with the platform, operating system, and language pack.) 2. To start the installation, click Open. 3. Follow the instructions on the installation wizard pages.

You can also save the Windows PowerShell files to a network share for installation on multiple computers. To perform a silent installation, type: /quiet

For example,PowerShellSetup_x86_fre.exe /quiet

On 32-bit versions of Windows, Windows PowerShell is installed, by default, in the %SystemRoot%\System32\WindowsPowerShell\v1.0 directory. On 64-bit versions of Windows, a 32-bit version of Windows PowerShell is installed in the %SystemRoot %\SystemWow64\WindowsPowerShell\v1.0 directory and a 64-bit version of Windows

PowerShell is installed in the %SystemRoot%\System32\WindowsPowerShell\v1.0 directory.

Running Windows PowerShellTo start Windows PowerShell from the Start Menu, click Start, click All Programs, click Windows PowerShell 1.0, and then click the Windows PowerShell icon. To start Windows PowerShell from the Run box, click Start, click Run, type powershell, and click OK. To start Windows PowerShell from a Command Prompt (cmd.exe) window, at the command prompt, type powershell. Because Windows PowerShell runs in a console session, you can use this same technique to run it within a remote telnet or SSH session. To return to your Command Prompt session, type exit.

Windows PowerShell BasicsGraphical interfaces use some basic concepts that are well known to most computer users. Users rely on the familiarity of those interfaces to to accomplish tasks. Operating systems present users with a graphical representation of items that can be browsed, usually with drop-down menus for accessing specific functionality and context menus for accessing context-specific functionality. A command-line interface (CLI), such as Windows PowerShell, must use a different approach to expose information, because it does not have menus or graphical systems to help the user. You need to know command names before you can use them. Although you can type complex commands that are equivalent to the features in a GUI environment, you must become familiar with commonly-used commands and command parameters. Most CLIs do not have patterns that can help the user to learn the interface. Because CLIs were the first operating system shells, many command names and parameter names were selected arbitrarily. Terse command names were generally chosen over clear ones. Although help systems and command design standards are integrated into most CLIs, they have been generally designed for compatibility with the earliest commands, so the command set is still shaped by decisions made decades ago. Windows PowerShell was designed to take advantage of a user's historic knowledge of CLIs. In this chapter, we will talk about some basic tools and concepts that you can use to learn Windows PowerShell quickly. They include: Using Get-Command

13 Using Cmd.exe and UNIX commands Using External Commands Using Tab-Completion Using Get-Help

Understanding Important Windows PowerShell ConceptsThe Windows PowerShell design integrates concepts from many different environments. Several of them are familiar to people with experience in specific shells or programming environments, but very few people will know about all of them. Looking at some of these concepts provides a useful overview of the shell.

Commands are not Text-basedUnlike traditional command-line interface commands, Windows PowerShell cmdlets are designed to deal with objects - structured information that is more than just a string of characters appearing on the screen. Command output always carries along extra information that you can use if you need it. We will discuss this topic in depth in this document. If you have used text-processing tools to process command-line data in the past, you will find that they behave differently if you try to use them in Windows PowerShell. In most cases, you do not need text-processing tools to extract specific information. You can access portions of the data directly by using standard Windows PowerShell object manipulation commands.

The Command Family is ExtensibleInterfaces such as Cmd.exe do not provide a way for you to directly extend the built-in command set. You can create external command-line tools that run in Cmd.exe, but these external tools do not have services, such as help integration, and Cmd.exe does not automatically know that they are valid commands. The native binary commands in Windows PowerShell, known as cmdlets (pronounced command-lets), can be augmented by cmdlets that you create and that you add to Windows PowerShell by using snap-ins. Windows PowerShell snap-ins are compiled, just like binary tools in any other interface. You can use them to add Windows PowerShell

providers to the shell, as well as new cmdlets. Because of the special nature of the Windows PowerShell internal commands, we will refer to them as cmdlets. Note: Windows PowerShell can run commands other than cmdlets. We will not be discussing them in detail in the Windows PowerShell Primer, but they are useful to know about as categories of command types. Windows PowerShell supports scripts that are analogous to UNIX shell scripts and Cmd.exe batch files, but have a .ps1 file name extension. Windows PowerShell also allows you to create internal functions that can be used directly in the interface or in scripts.

Windows PowerShell Handles Console Input and DisplayWhen you type a command, Windows PowerShell always processes the command-line input directly. Windows PowerShell also formats the output that you see on the screen. This is significant because it reduces the work required of each cmdlet and ensures that you can always do things the same way regardless of which cmdlet you are using. One example of how this simplifies life for both tool developers and users is command-line help. Traditional command-line tools have their own schemes for requesting and displaying help. Some command-line tools use /? to trigger the help display; others use -?, /H, or even //. Some will display help in a GUI window, rather than in the console display. Some complex tools, such as application updaters, unpack internal files before displaying their help. If you use the wrong parameter, the tool might ignore what you typed and begin performing a task automatically. When you enter a command in Windows PowerShell, everything you enter is automatically parsed and pre-processed by Windows PowerShell. If you use the -? parameter with a Windows PowerShell cmdlet, it always means "show me help for this command". Cmdlet developers do not have to parse the command; they only need to provide the help text. It is important to understand that the help features of Windows PowerShell are available even when you run traditional command-line tools in Windows PowerShell. Windows PowerShell processes the parameters and passes the results to the external tools. Note: If you run an graphic application in Windows PowerShell, the window for the application opens. Windows PowerShell intervenes only when processing the command-line input you supply or the application output returned to the console window; it does not affect how the application works internally.

15

Windows PowerShell Uses Some C# SyntaxWindows PowerShell has syntax features and keywords that are very similar to those used in the C# programming language, because Windows PowerShell is based on the .NET framework. Learning Windows PowerShell will make it much easier to learn C#, if you are interested in the language. If you are not a C# programmer, this similarity is not important. However, if you are already familiar with C#, the similarities can make learning Windows PowerShell much easier.

Learning Windows PowerShell NamesLearning names of commands and command parameters is a significant time investment with most command-line interfaces. The issue is that there are very few patterns, so the only way to learn is by memorizing each command and each parameter that you need to use on a regular basis. When you work with a new command or parameter, you cannot generally use what you already know; you have to find and learn a new name. If you look at how interfaces grow from a small set of tools with incremental additions to functionality, it is easy to see why the structure is nonstandard. With command names in particular, this may sound logical since each command is a separate tool, but there is a better way to handle command names. Most commands are built to manage elements of the operating system or applications, such as services or processes. The commands have a variety of names that may or may not fit into a family. For example, on Windows systems, you can use the net start and net stop commands to start and stop a service. There is another more generalized service control tool for Windows that has a completely different name, sc, that does not fit into the naming pattern for the net service commands. For process management, Windows has the tasklist command to list processes and the taskkill command to kill processes. Commands that take parameters have irregular parameter specifications. You cannot use the net start command to start a service on a remote computer. The sc command will start a service on a remote computer, but to specify the remote computer, you must prefix its name with a double backslash. For example, to start the spooler service on a remote computer named DC01, you would type sc \\DC01 start spooler. To list tasks running on DC01, you need to use the /S (for "system") parameter and supply the name DC01 without backslashes, like this: tasklist /S DC01. Although there are important technical distinctions between a service and a process, they are both examples of manageable elements on a computer that have a well-defined life cycle. You may want to start or stop a service or process, or get a list of all currently

running services or processes. In other words, although a service and a process are different things, the actions we perform on a service or a process are often conceptually the same. Furthermore, choices we may make to customize an action by specifying parameters may be conceptually similar as well. Windows PowerShell exploits these similarities to reduce the number of distinct names you need to know to understand and use cmdlets.

Cmdlets Use Verb-Noun Names to Reduce Command MemorizationWindows PowerShell uses a "verb-noun" naming system, where each cmdlet name consists of a standard verb hyphenated with a specific noun. Windows PowerShell verbs are not always English verbs, but they express specific actions in Windows PowerShell. Nouns are very much like nouns in any language, they describe specific types of objects that are important in system administration. It is easy to demonstrate how these two-part names reduce learning effort by looking at a few examples of verbs and nouns. Nouns are less restricted, but they should always describe what a command acts upon. Windows PowerShell has commands such as Get-Process, Stop-Process, Get-Service, and Stop-Service. In the case of two nouns and two verbs, consistency does not simplify learning that much. However, if you look at a standard set of 10 verbs and 10 nouns, you then have only 20 words to understand, but those words can be used to form 100 distinct command names. Frequently, you can recognize what a command does by reading its name, and it is usually apparent what name should be used for a new command. For example, a computer shutdown command might be Stop-Computer. A command that lists all computers on a network might be Get-Computer. The command that gets the system date is Get-Date. You can list all commands that include a particular verb with the -Verb parameter for GetCommand (We will discuss Get-Command in detail in the next section). For example, to see all cmdlets that use the verb Get, type:PS> Get-Command CommandType ----------Cmdlet Cmdlet Cmdlet Cmdlet ... -Verb Get Name ---Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Definition ---------Get-Acl [[-Path] ]... Get-Alias [[-Name] Get-Command -CommandType ExternalScript

Getting Detailed Help InformationWindows PowerShell has detailed help documentation for all cmdlets. To display the help topics, use the Get-Help cmdlet. For example, to get help for the Get-Childitem cmdlet, type:get-help get-childitem

orget-childitem -?

You can also display one page of each help topic at a time by using the man and help functions. To use them, type man or help followed by the cmdlet name. For example, to display help for the Get-Childitem cmdlet, typeman get-childitem

orhelp get-childitem

The Get-Help cmdlet also display information about conceptual topics in Windows

21 PowerShell. Conceptual help topics begin with the "about_" prefix, such as about_line_editing. To display a list of conceptual topics, type:get-help about_*

To display a particular help topic, type the topic name, for example:get-help about_line_editing

Using Familiar Command NamesUsing a mechanism called aliasing, Windows PowerShell allows users to refer to commands by alternate names. Aliasing allows users with experience in other shells to reuse common command names that they already know to perform similar operations in Windows PowerShell. Although we will not discuss Windows PowerShell aliases in detail, you can still use them as you get started with Windows PowerShell. Aliasing associates a command name that you type with another command. For example, Windows PowerShell has an internal function named Clear-Host that clears the output window. If you type either the cls or clear command at a command prompt, Windows PowerShell interprets that this is an alias for the Clear-Host function and runs the ClearHost function. This feature helps users to learn Windows PowerShell. First, most Cmd.exe and UNIX users have a large repertoire of commands that users already know by name, and although the Windows PowerShell equivalents may not produce identical results, they are close enough in form that users can use them to do work without having to first memorize the Windows PowerShell names. Second, the major source of frustration in learning a new shell when the user is already familiar with another shell, is the errors that are caused by "finger memory". If you have used Cmd.exe for years, when you have a screen full of output and want to clean it up, you would reflexively type the cls command and press the ENTER key. Without the alias to the Clear-Host function in Windows PowerShell, you would simply get the error message "'cls' is not recognized as a cmdlet, function, operable program, or script file." and be left with no idea of what to do to clear the output. The following is a brief listing of the common Cmd.exe and UNIX commands that you can use inside Windows PowerShell: cat cd dir echo mount move rm rmdir

chdir clear cls copy del diff

erase h history kill lp ls

popd ps pushd pwd r ren

sleep sort tee type write

If you find yourself using one of these commands reflexively and want to learn the real name of the native Windows PowerShell command, you can use the Get-Alias command:PS> Get-Alias cls CommandType ----------Alias Name ---cls Definition ---------Clear-Host

To make examples more readable, the Windows PowerShell Primer generally avoids using aliases. However, knowing more about aliases this early can still be useful if you are working with arbitrary snippets of Windows PowerShell code from another source or wish to define your own aliases. The rest of this section will discuss standard aliases and how to define your own aliases.

Interpreting Standard AliasesUnlike the aliases described above, which were designed for name-compatibility with other interfaces, the aliases built into Windows PowerShell are generally designed for brevity. These shorter names can be typed quickly, but are impossible to read if you do not know what they refer to. Windows PowerShell tries to compromise between clarity and brevity by providing a set of standard aliases that are based on shorthand names for common verbs and nouns. This allows a core set of aliases for common cmdlets that are readable once you know the shorthand names. For example, in standard aliases the verb Get is abbreviated to g, the verb Set is abbreviated to s, the noun Item is abbreviated to i, the noun Location is abbreviated to l, and the noun Command is abbreviated to cm. Here is a brief example to illustrate how this works. The standard alias for Get-Item comes from combining g for Get and i for Item: gi. The standard alias for Set-Item comes from combining s for Set and i for Item: si. The standard alias for Get-Location comes from combining g for Get and l for Location, gl. The standard alias for Set-Location comes from combining s for Set and l for Location, sl. The standard alias for Get-Command comes from

23 combining g for Get and cm for Command, gcm. There is no Set-Command cmdlet, but if there were, we would be able to guess that the standard alias comes from s for Set and cm for Command: scm. Furthermore, people familiar with Windows PowerShell aliasing who encounter scm would be able to guess that the alias refers to Set-Command.

Creating New AliasesYou can create your own aliases using the Set-Alias cmdlet. For example, the following statements create the standard cmdlet aliases discussed in Interpreting Standard Aliases:Set-Alias Set-Alias Set-Alias Set-Alias Set-Alias -Name -Name -Name -Name -Name gi -Value Get-Item si -Value Set-Item gl -Value Get-Location sl -Value Set-Location gcm -Value Get-Command

Internally, Windows PowerShell uses commands like these during startup, but these aliases are not changeable. If you attempt to actually execute one of these commands, you will get an error explaining that the alias cannot be modified. For example:PS> Set-Alias -Name gi -Value Get-Item Set-Alias : Alias is not writeable because alias gi is read-only or constant and cannot be written to. At line:1 char:10 + Set-Alias Get-Content c:\windows\acts

When you press the Tab key, the command expands to:PS> Get-Content C:\windows\actsetup.log

Note: One limitation of the tab expansion process is that tabs are always interpreted as attempts to complete a word. If you copy and paste command examples into a Windows PowerShell console, make sure that the sample does not contain tabs; if it does, the results will be unpredictable and will almost certainly not be what you intended.

Object PipelinePipelines act like a series of connected segments of pipe. Items moving along the pipeline pass through each segment. To create a pipeline in Windows PowerShell, you connect commands together with the pipe operator "|" and the output of each command is used as

25 input to the next command. Pipelines are arguably the most valuable concept used in command-line interfaces. Properly used, pipelines not only reduce the effort involved in entering complex commands, but also make it easier to see the flow of work in the commands. A related useful characteristic of pipelines is that since they operate on each item separately, you do not have to modify them based on whether you will have zero, one, or many items in the pipeline. Furthermore, each command in a pipeline (called a pipeline element) usually passes its output to the next command in the pipeline item-by-item. This usually reduces the resource demand of complex commands and allows you to begin getting the output immediately. In this chapter, we will describe how the Windows PowerShell pipeline differs from the pipelines of most popular shells, and then demonstrate some basic tools that you can use to help control pipeline output and also to see how the pipeline operates.

Understanding the Windows PowerShell PipelinePiping works virtually everywhere in Windows PowerShell. Although you see text on the screen, Windows PowerShell does not pipe text between commands. Instead, it pipes objects. The notation used for pipelines is similar to that used in other shells, so at first glance, it may not be apparent that Windows PowerShell introduces something new. For example, if you use the Out-Host cmdlet to force a page-by-page display of output from another command, the output looks just like the normal text displayed on the screen, broken up into pages:PS> Get-ChildItem -Path C:\WINDOWS\System32 | Out-Host -Paging Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\WINDOWS\system32 Mode ----a---a---a---a---a---a---a---a---a---a--LastWriteTime ------------2005-10-22 11:04 PM 2004-08-04 8:00 AM 2004-08-04 8:00 AM 2004-08-04 8:00 AM 2004-08-04 8:00 AM 2004-08-04 8:00 AM 2004-08-04 8:00 AM 2004-08-04 8:00 AM 2004-08-04 8:00 AM 2004-08-04 8:00 AM Length -----315 68608 64512 183808 61952 129536 114688 194048 111104 4096 Name ---$winnt$.inf access.cpl acctres.dll accwiz.exe acelpdec.ax acledit.dll aclui.dll activeds.dll activeds.tlb actmovie.exe

-a---a---a-- next ...

2004-08-04 8:00 AM 101888 actxprxy.dll 2003-02-21 6:50 PM 143150 admgmt.msc 2006-01-25 3:35 PM 53760 admparse.dll page; next line; Q quit

The Out-Host -Paging command is a useful pipeline element whenever you have lengthy output that you would like to display slowly .It is especially useful if the operation is very CPU-intensive. Since processing is transferred to the Out-Host cmdlet when it has a complete page ready to display, cmdlets that proceed it in the pipeline halt operation until the next page of output is available. You can see this if you use the Windows Task Manager to monitor CPU and memory use by Windows PowerShell. Run the following command: Get-ChildItem C:\Windows -Recurse. Compare the CPU and memory usage to this command: Get-ChildItem C:\Windows -Recurse | Out-Host -Paging. What you see on the screen is text, but that is because it is necessary to represent objects as text in a console window. This is really just a representation of what is really going on inside Windows PowerShell. For example, consider the Get-Location cmdlet. If you type Get-Location while your current location is the root of the C drive, you would see the following output:PS> Get-Location Path ---C:\

If Windows PowerShell pipelined text, issuing a command such as Get-Location | OutHost, would pass from Get-Location to Out-Host a set of characters in the order they are displayed onscreen. In other words, if you were to ignore the heading information, OutHost would first receive the character 'C', then the character ':', then the character '\'. The Out-Host cmdlet could not determine what meaning to associate with the characters output by the Get-Location cmdlet. Instead of using text to let commands in a pipeline communicate, Windows PowerShell uses objects. From the standpoint of a user, objects package related information into a form that makes it easier to manipulate the information as a unit, and extract specific items that you need. The Get-Location command does not return text that contains the current path. It returns a package of information called a PathInfo object that contains the current path along with some other information. The Out-Host cmdlet then sends this PathInfo object to the screen, and Windows PowerShell decides what information to display and how to display it based on its formatting rules.

27 In fact, the heading information output by the Get-Location cmdlet is added only at the end of the process, as part of the process of formatting the data for onscreen display. What you see onscreen is a summary of information, and not a complete representation of the output object. Given that there may be more information output from a Windows PowerShell command than what we see displayed in the console window, how can you retrieve the non-visible elements? How do you view the extra data? And what if you want to view the data in a format different than the one Windows PowerShell normally uses? The rest of this chapter discusses how you can discover the structure of specific Windows PowerShell objects, selecting specific items and formatting them for easier display, and how to send this information to alternative output locations such as files and printers.

Viewing Object Structure (Get-Member)Because objects play such a central role in Windows PowerShell, there are several native commands designed to work with arbitrary object types. The most important one is the GetMember command. The simplest technique for analyzing the objects that a command returns is to pipe the output of that command to the Get-Member cmdlet. The Get-Member cmdlet shows you the formal name of the object type and a complete listing of its members. The number of elements that are returned can sometimes be overwhelming. For example, a process object can have over 100 members. To see all of the members of a Process object and page the output so you can view all of it, type:PS> Get-Process | Get-Member | Out-Host -Paging

The output from this command will look something like this:TypeName: System.Diagnostics.Process Name ---Handles Name NPM PM VM WS add_Disposed ... MemberType ---------AliasProperty AliasProperty AliasProperty AliasProperty AliasProperty AliasProperty Method Definition ---------Handles = Handlecount Name = ProcessName NPM = NonpagedSystemMemorySize PM = PagedMemorySize VM = VirtualMemorySize WS = WorkingSet System.Void add_Disposed(Event...

We can make this long list of information more usable by filtering for elements we want to see. The Get-Member command lets you list only members that are properties. There are several forms of properties. The cmdlet displays properties of any type if we set the GetMemberMemberType parameter to the value Properties. The resulting list is still very long, but a bit more manageable:PS> Get-Process | Get-Member -MemberType Properties

TypeName: System.Diagnostics.Process Name ---Handles Name ... ExitCode ... Handle ... CPU ... Path ... MemberType ---------AliasProperty AliasProperty Property Property Definition ---------Handles = Handlecount Name = ProcessName System.Int32 ExitCode {get;} System.IntPtr Handle {get;}

ScriptProperty System.Object CPU {get=$this.Total... ScriptProperty System.Object Path {get=$this.Main...

Note: The allowed values of MemberType are AliasProperty, CodeProperty, Property, NoteProperty, ScriptProperty, Properties, PropertySet, Method, CodeMethod, ScriptMethod, Methods, ParameterizedProperty, MemberSet, and All. There are over 60 properties for a process. The reason Windows PowerShell often shows only a handful of properties for any well-known object is that showing all of them would produce an unmanageable amount of information. Note: Windows PowerShell determines how to display an object type by using information stored in XML files that have names ending in .format.ps1xml. The formatting data for process objects, which are .NET System.Diagnostics.Process objects, is stored in PowerShellCore.format.ps1xml. If you need to look at properties other than those that Windows PowerShell displays by default, you will need to format the output data yourself. This can be done by using the format cmdlets.

29

Using Format Commands to Change Output ViewWindows PowerShell has a set of cmdlets that allow you to control which properties are displayed for particular objects. The names of all the cmdlets begin with the verb Format. They let you select one or more properties to show. The Format cmdlets are Format-Wide, Format-List, Format-Table, and Format-Custom. We will only describe the Format-Wide, Format-List, and Format-Table cmdlets in this primer. Each format cmdlet has default properties that will be used if you do not specify specific properties to display. Each cmdlet also uses the same parameter name, Property, to specify which properties you want to display. Because Format-Wide only shows a single property, its Property parameter only takes a single value, but the property parameters of Format-List and Format-Table will accept a list of property names. If you use the command Get-Process -Name powershell with 2 instances of Windows PowerShell running, you get output that looks like this:Handles ------995 331 NPM(K) -----9 9 PM(K) ----30308 23284 WS(K) VM(M) ----- ----27996 152 29084 143 CPU(s) -----2.73 1.06 Id -2760 3448 ProcessName ----------powershell powershell

In the rest of this section, we will explore how to use Format cmdlets to change the way the output of this command is displayed.

Using Format-Wide for Single-Item OutputThe Format-Wide cmdlet, by default, displays only the default property of an object. The information associated with each object is displayed in a single column:PS> Get-Process -Name powershell | Format-Wide powershell powershell

You can also specify a non-default property:PS> Get-Process -Name powershell | Format-Wide -Property Id 2760 3448

Controlling Format-Wide Display with ColumnWith the Format-Wide cmdlet, you can only display a single property at a time. This makes it useful for displaying simple lists that show only one element per line. To get a simple listing, set the value of the Column parameter to 1 by typing:Get-Command Format-Wide -Property Name -Column 1

Using Format-List for a List ViewThe Format-List cmdlet displays an object in the form of a listing, with each property labeled and displayed on a separate line:PS> Get-Process -Name powershell | Format-List Id Handles CPU Name Id Handles CPU Name : : : : : : : : 2760 1242 3.03125 powershell 3448 328 1.0625 powershell

You can specify as many properties as you want:PS> Get-Process -Name powershell | Format-List -Property ProcessName,FileVersion ,StartTime,Id

ProcessName FileVersion StartTime Id ProcessName FileVersion StartTime Id

: : : : : : : :

powershell 1.0.9567.1 2006-05-24 13:42:00 2760 powershell 1.0.9567.1 2006-05-24 13:54:28 3448

Getting Detailed Information by using Format-List with WildcardsThe Format-List cmdlet lets you use a wildcard as the value of its Property parameter. This lets you display detailed information. Often, objects include more information than you need, which is why Windows PowerShell does not show all property values by default. To show all of properties of an object, use the Format-List -Property * command. The

31 following command generates over 60 lines of output for a single process:Get-Process -Name powershell | Format-List -Property *

Although the Format-List command is useful for showing detail, if you want an overview of output that includes many items, a simpler tabular view is often more useful.

Using Format-Table for Tabular OutputIf you use the Format-Table cmdlet with no property names specified to format the output of the Get-Process command, you get exactly the same output as you do without performing any formatting. The reason is that processes are usually displayed in a tabular format, as are most Windows PowerShell objects.PS> Get-Process -Name powershell | Format-Table Handles ------1488 332 NPM(K) -----9 9 PM(K) ----31568 23140 WS(K) VM(M) ----- ----29460 152 632 141 CPU(s) -----3.53 1.06 Id -2760 3448 ProcessName ----------powershell powershell

Improving Format-Table Output (AutoSize)Although a tabular view is useful for displaying a lot of comparable information, it may be difficult to interpret if the display is too narrow for the data. For example, if you try to display process path, ID, name, and company, you get truncated output for the process path and the company column:PS> Get-Process -Name powershell | Format-Table -Property Path,Name,Id,Company Path Name ------C:\Program Files... powershell Id Company -- ------2836 Microsoft Corpor...

If you specify the AutoSize parameter when you run the Format-Table command, Windows PowerShell will calculate column widths based on the actual data you are going to display. This makes the Path column readable, but the company column remains truncated:PS> Get-Process -Name powershell | Format-Table -Property Path,Name,Id,Company AutoSize Path Name Id Company -------- ------C:\Program Files\Windows PowerShell\v1.0\powershell.exe powershell 2836 Micr...

The Format-Table cmdlet might still truncate data, but it will only do so at the end of the screen. Properties, other than the last one displayed, are given as much size as they need for their longest data element to display correctly. You can see that company name is visible but path is truncated if you swap the locations of Path and Company in the Property value list:PS> Get-Process -Name powershell | Format-Table -Property Company,Name,Id,Path AutoSize Company Name Id Path ----------- ---Microsoft Corporation powershell 2836 C:\Program Files\Windows PowerShell\v1...

The Format-Table command assumes that the nearer a property is to the beginning of the property list, the more important it is. So it attempts to display the properties nearest the beginning completely. If the Format-Table command cannot display all of the properties, it will remove some columns from the display and provide a warning. You can see this behavior if you make Name the last property in the list:PS> Get-Process -Name powershell | Format-Table -Property Company,Path,Id,Name AutoSize WARNING: column "Name" does not fit into the display and was removed. Company I d ---------Microsoft Corporation C:\Program Files\Windows PowerShell\v1.0\powershell.exe 6 Path

In the output above, the ID column is truncated to make it fit into the listing, and the column headings are stacked up. Automatically resizing the columns does not always do what you want.

Wrapping Format-Table Output in Columns (Wrap)You can force lengthy Format-Table data to wrap within its display column by using the Wrap parameter. Using the Wrap parameter alone will not necessarily do what you expect, since it uses default settings if you do not also specify AutoSize:PS> Get-Process -Name powershell | Format-Table -Wrap -Property Name,Id,Company, Path Name ---powershell Id Company Path -- ---------2836 Microsoft Corporati C:\Program Files\Wi on ndows PowerShell\v1 .0\powershell.exe

33 An advantage of using the Wrap parameter by itself is that it does not slow down processing very much. If you perform a recursive file listing of a large directory system, it might take a very long time and use a lot of memory before displaying the first output items if you use AutoSize. If you are not concerned about system load, then AutoSize works well with the Wrap parameter. The initial columns are always allotted as much width as they need to display items on one line, just as when you specify AutoSize without the Wrap parameter. The only difference is that the final column will be wrapped if necessary:PS> Get-Process -Name powershell | Format-Table -Wrap -AutoSize -Property Name,I d,Company,Path Name Id Company Path ----- ---------powershell 2836 Microsoft Corporation C:\Program Files\Windows PowerShell\v1.0\ powershell.exe

Some columns might not be displayed if you specify the widest columns first, so it is safest to specify the smallest data elements first. In the following example, we specify the extremely wide path element first, and even with wrapping, we still lose the final Name column:PS> Get-Process -Name powershell | Format-Table -Wrap -AutoSize -Property Path,I d,Company,Name WARNING: column "Name" does not fit into the display and was removed. Path Id Company ----- ------C:\Program Files\Windows PowerShell\v1.0\powershell.exe 2836 Microsoft Corporat ion

Organizing Table Output (-GroupBy)Another useful parameter for tabular output control is GroupBy. Longer tabular listings in particular may be hard to compare. The GroupBy parameter groups output based on a property value. For example, we can group processes by company for easier inspection, omitting the company value from the property listing:PS> Get-Process -Name powershell | Format-Table -Wrap -AutoSize -Property Name,I d,Path -GroupBy Company

Company: Microsoft Corporation Name ---Id Path -- ----

powershell 1956 C:\Program Files\Windows PowerShell\v1.0\powershell.exe powershell 2656 C:\Program Files\Windows PowerShell\v1.0\powershell.exe

Redirecting Data with Out-* CmdletsWindows PowerShell provides several cmdlets that let you control data output directly. These cmdlets share two important characteristics. First, they generally transform data to some form of text. They do this because they output the data to system components that require text input. This means they need to represent the objects as text. Therefore, the text is formatted as you see it in the Windows PowerShell console window. Second, these cmdlets use the Windows PowerShell verb Out because they send information out from Windows PowerShell to somewhere else. The Out-Host cmdlet is no exception: the host window display is outside of Windows PowerShell. This is important because when data is sent out of Windows PowerShell, it is actually removed. You can see this if you try to create a pipeline that pages data to the host window, and then attempt to format it as a list, as shown here:PS> Get-Process | Out-Host -Paging | Format-List

You might expect the command to display pages of process information in list format. Instead, it displays the default tabular list:Handles NPM(K) ------- -----101 5 ... 618 18 257 8 ... next page; ... PM(K) ----1076 39348 9752 WS(K) VM(M) ----- ----3316 32 51108 16828 143 79 CPU(s) -----0.05 211.20 3.02 Id ProcessName -- ----------2888 alg 740 explorer 2560 explorer

next line; Q quit

The Out-Host cmdlet sends the data directly to the console, so the Format-List command never receives anything to format. The correct way to structure this command is to put the Out-Host cmdlet at the end of the pipeline as shown below. This causes the process data to be formatted in a list before being paged and displayed.PS> Get-Process | Format-List | Out-Host -Paging

35Id Handles CPU Name ... Id Handles CPU Name Id Handles CPU Name ... ... : : : : 2888 101 0.046875 alg

: : : : : : : :

740 612 211.703125 explorer 2560 257 3.015625 explorer

next page; next line; Q quit

This applies to all of the Out cmdlets. An Out cmdlet should always appear at the end of the pipeline. Note: All the Out cmdlets render output as text, using the formatting in effect for the console window, including line length limits.

Paging Console Output (Out-Host)By default, Windows PowerShell sends data to the host window, which is exactly what the Out-Host cmdlet does. The primary use for the Out-Host cmdlet is paging data as we discussed earlier. For example, the following command uses Out-Host to page the output of the Get-Command cmdlet:PS> Get-Command | Out-Host -Paging

You can also use the more function to page data. In Windows PowerShell, more is a function that calls Out-Host -Paging. The following command demonstrates using the more function to page the output of Get-Command:PS> Get-Command | more

If you include one or more filenames as arguments to the more function, the function will read the specified files and page their contents to the host:PS> more c:\boot.ini [boot loader] timeout=5

default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS [operating systems] ...

Discarding Output (Out-Null)The Out-Null cmdlet is designed to immediately discard any input it receives. This is useful for discarding unnecessary data that you get as a side-effect of running a command. When type the following command, you do not get anything back from the command:PS> Get-Command | Out-Null

The Out-Null cmdlet does not discard error output. For example, if you enter the following command, a message is displayed informing you that Windows PowerShell does not recognize 'Is-NotACommand':PS> Get-Command Is-NotACommand | Out-Null Get-Command : 'Is-NotACommand' is not recognized as a cmdlet, function, operabl e program, or script file. At line:1 char:12 + Get-Command Get-Process | Out-File -FilePath C:\temp\processlist.txt -Encoding ASCII

Out-file formats file contents to look like console output. This causes the output to be truncated just as it is in a console window in most circumstances. For example, if you run the following command:PS> Get-Command | Out-File -FilePath c:\temp\output.txt

The output will look like this:CommandType ----------Cmdlet Cmdlet ... Name ---Add-Content Add-History Definition ---------Add-Content [-Path] Get-Location Path ---C:\Documents and Settings\PowerUser

Note: The Get-Location cmdlet is similar to the pwd command in the BASH shell. The Set-Location cmdlet is similar to the cd command in Cmd.exe.

Setting Your Current Location (Set-Location)The Get-Location command is used with the Set-Location command. The Set-Location command allows you to specify your current directory location.PS> Set-Location -Path C:\Windows

39 After you enter the command, you will notice that you do not receive any direct feedback about the effect of the command. Most Windows PowerShell commands that perform an action produce little or no output because the output is not always useful. To verify that a successful directory change has occurred when you enter the Set-Location command, include the -PassThru parameter when you enter the Set-Location command:PS> Set-Location -Path C:\Windows -PassThru Path ---C:\WINDOWS

The -PassThru parameter can be used with many Set commands in Windows PowerShell to return information about the result in cases in which there is no default output. You can specify paths relative to your current location in the same way as you would in most UNIX and Windows command shells. In standard notation for relative paths, a period (.)represents your current folder, and a doubled period (..) represents the parent directory of your current location. For example, if you are in the C:\Windows folder, a period (.)represents C:\Windows and double periods (..) represent C:. You can change from your current location to the root of the C: drive by typing:PS> Set-Location -Path .. -PassThru Path ---C:\

The same technique works on Windows PowerShell drives that are not file system drives, such as HKLM:. You can set your location to the HKLM\Software key in the registry by typing:PS> Set-Location -Path HKLM:\SOFTWARE -PassThru Path ---HKLM:\SOFTWARE

You can then change the directory location to the parent directory, which is the root of the Windows PowerShell HKLM: drive, by using a relative path:PS> Set-Location -Path .. -PassThru Path ---HKLM:\

You can type Set-Location or use any of the built-in Windows PowerShell aliases for SetLocation (cd, chdir, sl). For example:cd -Path C:\Windows

chdir -Path .. -PassThru sl -Path HKLM:\SOFTWARE -PassThru

Saving and Recalling Recent Locations (Push-Location and Pop-Location)When changing locations, it is helpful to keep track of where you have been and to be able to return to your previous location. The Push-Location cmdlet in Windows PowerShell creates a ordered history (a "stack") of directory paths where you have been, and you can step back through the history of directory paths by using the complementary Pop-Location cmdlet. For example, a Windows PowerShell session typically starts in the user's home directory.PS> Get-Location Path ---C:\Documents and Settings\PowerUser

Note: The word stack has a special meaning in many programming settings, including .NET. Like a physical stack of items, the last item you put onto the stack is the first item that you can pull off the stack. Adding an item to a stack is colloquially known as "pushing" the item onto the stack. Pulling an item off the stack is colloquially known as "popping" the item off the stack.

To push the current location onto the stack, and then move to the Local Settings folder, type:PS> Push-Location -Path "Local Settings"

You can then push the Local Settings location onto the stack and and move to the Temp folder by typing:

41PS> Push-Location -Path Temp

You can verify that you changed directories by entering the Get-Location command:PS> Get-Location Path ---C:\Documents and Settings\PowerUser\Local Settings\Temp

You can then pop back into the most recently visited directory by entering the PopLocation command, and verify the change by entering the Get-Location command:PS> Pop-Location PS> Get-Location Path ---C:\Documents and Settings\me\Local Settings

Just as with the Set-Location cmdlet, you can include the -PassThru parameter when you enter the Pop-Location cmdlet to display the directory that you entered:PS> Pop-Location -PassThru Path ---C:\Documents and Settings\PowerUser

You can also use the Location cmdlets with network paths. If you have a server named FS01 with an share named Public, you can change your location by typingSet-Location \\FS01\Public

orPush-Location \\FS01\Public

You can use the Push-Location and Set-Location commands to change the location to any available drive. For example, if you have a local CD-ROM drive with drive letter D that contains a data CD, you can change the location to the CD drive by entering the SetLocation D: command. If the drive is empty, you will get the following error message:PS> Set-Location D: Set-Location : Cannot find path 'D:\' because it does not exist.

When you are using a command-line interface, it is not convenient to use Windows Explorer to examine the available physical drives. Also, Windows Explorer would not show you the all of the Windows PowerShell drives. Windows PowerShell provides a set of commands for manipulating Windows PowerShell drives. and we will talk about these next.

Managing Windows PowerShell DrivesA Windows PowerShell drive is a data store location that you can access like a file system drive in Windows Powershell. The Windows PowerShell providers create some drives for you, such as the file system drives (including C: and D:), the registry drives (HKCU: and HKLM:), and the certificate drive (Cert:), and you can create your own Windows PowerShell drives. These drives are very useful, but they are available only within Windows PowerShell. You cannot access them by using other Windows tools, such as Windows Explorer or Cmd.exe. Windows PowerShell uses the noun, PSDrive, for commands that work with Windows PowerShell drives. For a list of the Windows PowerShell drives in your session, use the Get-PSDrive cmdlet.PS> Get-PSDrive Name ---A Alias C cert D Env Function HKCU HKLM Variable Provider -------FileSystem Alias FileSystem Certificate FileSystem Environment Function Registry Registry Variable Root ---A:\ C:\ \ D:\ CurrentLocation ---------------

...And Settings\me

HKEY_CURRENT_USER HKEY_LOCAL_MACHINE

Although the drives in the display vary with the drives on your system, the listing will look similar to the output of the Get-PSDrive command shown above. File system drives are a subset of the Windows PowerShell drives. You can identify the file system drives by the FileSystem entry in the Provider column. (The file system drives in Windows PowerShell are supported by the Windows PowerShell FileSystem provider.) To see the syntax of the Get-PSDrive cmdlet, type a Get-Command command with the Syntax parameter:PS> Get-Command -Name Get-PSDrive -Syntax

43Get-PSDrive [[-Name] ] [-Scope ] [-PSProvider ] [-V erbose] [-Debug] [-ErrorAction ] [-ErrorVariable ] [OutVariable ] [-OutBuffer ]

The PSProvider parameter lets you display only the Windows PowerShell drives that are supported by a particular provider. For example, to display only the Windows PowerShell drives that are supported by the Windows PowerShell FileSystem provider, type a GetPSDrive command with the PSProvider parameter and the FileSystem value:PS> Get-PSDrive -PSProvider FileSystem Name ---A C D Provider -------FileSystem FileSystem FileSystem Root ---A:\ C:\ D:\ CurrentLocation --------------...nd Settings\PowerUser

To view the Windows PowerShell drives that represent registry hives, use the PSProvider parameter to display only the Windows PowerShell drives that are supported by the Windows PowerShell Registry provider:PS> Get-PSDrive -PSProvider Registry

Name ---HKCU HKLM

Provider -------Registry Registry

Root ---HKEY_CURRENT_USER HKEY_LOCAL_MACHINE

CurrentLocation ---------------

You can also use the standard Location cmdlets with the Windows PowerShell drives:PS> Set-Location HKLM:\SOFTWARE PS> Push-Location .\Microsoft PS> Get-Location

Path ---HKLM:\SOFTWARE\Microsoft

Adding New Windows PowerShell Drives (New-PSDrive)You can add your own Windows PowerShell drives by using the New-PSDrive command. To get the syntax for the New-PSDrive command, enter the Get-Command command with the Syntax parameter:PS> Get-Command -Name New-PSDrive -Syntax New-PSDrive [-Name] [-PSProvider] [-Root] [-Descript ion ] [-Scope ] [-Credential ] [-Verbose] [-Debug ] [-ErrorAction ] [-ErrorVariable ] [-OutVariable ] [-OutBuffer ] [-WhatIf] [-Confirm]

To create a new Windows PowerShell drive, you must supply three parameters: A name for the drive (you can use any valid Windows PowerShell name) The PSProvider (use "FileSystem" for file system locations and "Registry" for registry locations) The root, that is, the path to the root of the new drive

For example, you can create a drive named "Office" that is mapped to the folder that contains the Microsoft Office applications on your computer, such as C:\Program Files\Microsoft Office\OFFICE11. To create the drive, type the following command:PS> New-PSDrive -Name Office -PSProvider FileSystem -Root "C:\Program Files\Micr osoft Office\OFFICE11" Name ---Office Provider -------FileSystem Root ---C:\Program Files\Microsoft Offic... CurrentLocation ---------------

Note: In general, paths are not case-sensitive.

You refer to the new Windows PowerShell drive as you do all Windows PowerShell drives -- by its name followed by a colon (:). A Windows PowerShell drive can make many tasks much simpler. For example, some of the most important keys in the Windows registry have extremely long paths, making them cumbersome to access and difficult to remember. Critical configuration information resides under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion. To view and change items in the CurrentVersion registry key, you can create a Windows PowerShell drive that is rooted in that key by typing:PS> New-PSDrive -Name cvkey -PSProvider Registry -Root HKLM\Software\Microsoft\W

45indows\CurrentVersion

Name ---cvkey

Provider -------Registry

Root ---HKLM\Software\Microsoft\Windows\...

CurrentLocation ---------------

You can then change location to the cvkey: drive as you would any other drive:PS> cd cvkey:

or:PS> Set-Location cvkey: -PassThru

Path ---cvkey:\

The New-PsDrive cmdlet adds the new drive only to the current console session. If you exit the console or close the Windows PowerShell window, the new drive is lost. To save a Windows PowerShell drive, use the Export-Console cmdlet to export the current console, and then use the PowerShell.exe PSConsoleFile parameter to import it into a new session. Or, add the new drive to your Windows PowerShell profile.

Deleting Windows PowerShell Drives (Remove-PSDrive)You can delete drives from Windows PowerShell by using the Remove-PSDrive cmdlet. The Remove-PSDrive cmdlet is easy to use; to delete a specific Windows PowerShell drive, you just supply the Windows PowerShell drive name. For example, if you added the Office: Windows PowerShell drive, as shown in the NewPSDrive topic, you can delete it by typing:PS> Remove-PSDrive -Name Office

To delete the cvkey: Windows PowerShell drive, also shown in the New-PSDrive topic, use the following command:PS> Remove-PSDrive -Name cvkey

It's easy to delete a Windows PowerShell drive, but you can't delete it while you are in the drive. For example:

PS> cd office: PS Office:\> remove-psdrive -name office Remove-PSDrive : Cannot remove drive 'Office' because it is in use. At line:1 char:15 + remove-psdrive Get-ChildItem -Path C:\WINDOWS -Recurse Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\WINDOWS Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\WINDOWS\AppPatch Mode LastWriteTime Length Name --------------------- ----a--2004-08-04 8:00 AM 1852416 AcGenral.dll ...

Filtering Items by Name (-Name)To display only the names of items, use the Name parameter of Get-Childitem:PS> Get-ChildItem -Path C:\WINDOWS -Name addins AppPatch assembly ...

Forcibly Listing Hidden Items (-Force)Items that are normally invisible in Windows Explorer or Cmd.exe are not displayed in the output of a Get-ChildItem command. To display hidden items, use the Force parameter of Get-ChildItem. For example:Get-ChildItem -Path C:\Windows -Force

This parameter is named Force because you can forcibly override the normal behavior of the Get-ChildItem command. Force is a widely used parameter that forces an action that a

cmdlet would not normally perform, although it will not perform any action that compromises the security of the system.

Matching Item Names with WildcardsThe Get-ChildItem command accepts wildcards in the path of the items to list. Because wildcard matching is handled by the Windows PowerShell engine, all cmdlets that accepts wildcards use the same notation and have the same matching behavior. The Windows PowerShell wildcard notation includes: Asterisk (*)matches zero or more occurrences of any character. Question mark (?) matches exactly one character. Left bracket ([) character and right bracket (]) character surround a set of characters to be matched.

Here are some examples of how wildcard specification works. To find all files in the Windows directory with the suffix .log and exactly five characters in the base name, enter the following command:PS> Get-ChildItem -Path C:\Windows\?????.log Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\Windows Mode LastWriteTime Length Name --------------------- ---... -a--2006-05-11 6:31 PM 204276 ocgen.log -a--2006-05-11 6:31 PM 22365 ocmsn.log ... -a--2005-11-11 4:55 AM 64 setup.log -a--2005-12-15 2:24 PM 17719 VxSDM.log ...

To find all files that begin with the letter x in the Windows directory, type:Get-ChildItem -Path C:\Windows\x*

To find all files whose names begin with x or z, type:Get-ChildItem -Path C:\Windows\[xz]*

Excluding Items (-Exclude)You can exclude specific items by using the Exclude parameter of Get-ChildItem. This lets you perform complex filtering in a single statement. For example, suppose you are trying to find the Windows Time Service DLL in the

49 System32 folder, and all you can remember about the DLL name is that it begins with "W" and has "32" in it. An expression like w*32*.dll will find all DLLs that satisfy the conditions, but it may also return the Windows 95 and 16-bit Windows compatibility DLLs that include "95" or "16" in their names. You can omit files that have any of these numbers in their names by using the Exclude parameter with the pattern *[9516]*:PS> Get-ChildItem -Path C:\WINDOWS\System32\w*32*.dll -Exclude *[9516]*

Directory: Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS\System32

Mode ----a---a---a---a---a---a---a---a---a---

LastWriteTime ------------2004-08-04 2004-08-04 2004-08-04 2004-08-04 2004-08-04 2004-08-04 2004-08-04 2004-08-04 2004-08-04 8:00 AM 8:00 AM 8:00 AM 8:00 AM 8:00 AM 8:00 AM 8:00 AM 8:00 AM 8:00 AM

Length Name ------ ---174592 w32time.dll 22016 w32topl.dll 101888 win32spl.dll 172032 wldap32.dll 264192 wow32.dll 82944 ws2_32.dll 42496 wsnmp32.dll 22528 wsock32.dll 18432 wtsapi32.dll

Mixing Get-ChildItem ParametersYou can use several of the parameters of the Get-ChildItem cmdlet in the same command. Before you mix parameters, be sure that you understand wildcard matching. For example, the following command returns no results:PS> Get-ChildItem -Path C:\Windows\*.dll -Recurse -Exclude [a-y]*.dll

There are no results, even though there are two DLLs that begin with the letter "z" in the Windows folder.

No results were returned because we specified the wildcard as part of the path. Even though the command was recursive, the Get-ChildItem cmdlet restricted the items to those that are in the Windows folder with names end with ".dll". To specify a recursive search for files whose names match a special pattern, use the -Include parameter.PS> Get-ChildItem -Path C:\Windows -Include *.dll -Recurse -Exclude [a-y]*.dll Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\Windows\System32\Setup

Mode ----a---

LastWriteTime ------------2004-08-04 8:00 AM

Length Name ------ ---8261 zoneoc.dll

Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\Windows\System32

Mode ----a---

LastWriteTime ------------2004-08-04 8:00 AM

Length Name ------ ---337920 zipfldr.dll

Manipulating Items DirectlyThe elements that you see in Windows PowerShell drives, such as the files and folders in the file system drives, and the registry keys in the Windows PowerShell registry drives, are called items in Windows PowerShell. The cmdlets for working with them item have the noun Item in their names. The output of the Get-Command -Noun Item command shows that there are nine Windows PowerShell item cmdlets.PS> Get-Command -Noun Item CommandType ----------Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Name ---Clear-Item Copy-Item Get-Item Invoke-Item Move-Item Definition ---------Clear-Item [-Path] New-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\_Test Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Micros oft\Windows\CurrentVersion SKC --0 VC Name -- ---0 _Test Property -------{}

When typing a registry path, be sure to include the colon (:) in the Windows PowerShell

drive names, HKLM: and HKCU:. Without the colon, Windows PowerShell does not recognize the drive name in the path.

Why Registry Values are not ItemsWhen you use the Get-ChildItem cmdlet to find the items in a registry key, you will never see actual registry entries or their values. For example, the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run usually contains several registry entries that represent applications that run when the system starts. However, when you use Get-ChildItem to look for child items in the key, all you will see is the OptionalComponents subkey of the key:PS> Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Run Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Micros oft\Windows\CurrentVersion\Run SKC VC Name Property --- -- ----------3 0 OptionalComponents {}

Although it would be convenient to treat registry entries as items, you cannot specify a path to a registry entry in a way that ensures that it is unique. The path notation does not distinguish between the registry subkey named Run and the (Default) registry entry in the Run subkey. Furthermore, because registry entry names can contain the backslash character (\), if regsitry entries were items, then you could not use the path notation to distinguish a registry entry named Windows\CurrentVersion\Run from the subkey that is located in that path.

Renaming Existing Items (Rename-Item)To change the name of a file or folder, use the Rename-Item cmdlet. The following command changes the name of the file1.txt file to fileOne.txt.PS> Rename-Item -Path C:\temp\New.Directory\file1.txt fileOne.txt

The Rename-Item cmdlet can change the name of a file or a folder, but it cannot move an item. The following command fails because it attempts to move the file from the New.Directory directory to the Temp directory.PS> Rename-Item -Path C:\temp\New.Directory\fileOne.txt c:\temp\fileOne.txt Rename-Item : Cannot rename because the target specified is not a path. At line:1 char:12 + Rename-Item Get-ChildItem -Path C:\temp\New.Directory PS>

Why doesn't the Copy-Item cmdlet copy the contents to the new location? The Copy-Item cmdlet was designed to be generic; it is not just for copying files and folders. Also, even when copying files and folders, you might want to copy only the container and not the items within it. To copy all of the contents of a folder, include the Recurse parameter of the Copy-Item cmdlet in the command. If you have already copied the directory without its contents, add the Force parameter, which allows you to overwrite the empty folder.PS> Copy-Item -Path C:\New.Directory -Destination C:\temp -Recurse -Force -Passthru

Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\temp Mode ---d---LastWriteTime ------------2006-05-18 1:53 PM Length Name ------ ---New.Directory

Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\temp\New.Directory Mode ----a--LastWriteTime ------------2006-05-18 11:44 AM Length Name ------ ---0 file1

Deleting Items (Remove-Item)To delete files and folders, use the Remove-Item cmdlet. Windows PowerShell cmdlets, such as Remove-Item, that can make significant, irreversible changes will often prompt for confirmation when you enter its commands. For example, if you try to remove the New.Directory folder, you will be prompted to confirm the command, because the folder contains files:PS> Remove-Item C:\New.Directory Confirm The item at C:\temp\New.Directory has children and the -recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to continue? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):

Because Yes is the default response, to delete the folder and its files, press the Enter key. To remove the folder withou