Windows PowerShell™ Getting Started Guide
Microsoft Corporation
Published: September 2006
Abstract
Windows 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 is designed to introduce new users to Windows PowerShell and to acquaint them with its basic features. For more detailed information, see the Windows PowerShell Primer.
Contents
This 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, Windows Server 2003, Windows Vista, .NET Framework 2.0, .NET Framework 2.0 Runtime Components, and Win32 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 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.
Unlike most shells, which accept and return text, Windows PowerShell is built on top of the .NET common language runtime (CLR) and the .NET Framework, and accepts and returns .NET objects. This fundamental change in the environment brings entirely new tools and methods to the management and configuration of Windows.
Windows PowerShell introduces the concept of a cmdlet (pronounced "command-let"), a simple, single-function command-line tool built into the shell. You can use each cmdlet separately, but their power is realized when you use these simple tools in combination to perform complex tasks. Windows PowerShell includes more than one hundred basic core cmdlets, and you can write your own cmdlets and share them with other users.
Like many shells, Windows PowerShell gives you access to the file system on the computer. In addition, Windows PowerShell providers enable you to access other data stores, such as the registry and the digital signature certificate stores, as easily as you access the file system.
This Getting Started guide provides an introduction to Windows PowerShell: the language, the cmdlets, the providers, and the use of objects.
Primary Focus
The primary focus of this document is to help Windows PowerShell users get started with Windows PowerShell. This document describes the features of the shell that you need to start using the shell. For a detailed examination of the shell, its features, and examples of how to use the shell, see the Windows PowerShell Primer.
Most shells, including Cmd.exe and the SH, KSH, CSH, and BASH Unix shells, operate by executing a command or utility in a new process, and presenting the results to the user as text. Over the years, many text processing utilities, such as sed, AWK, and PERL, have evolved to support this interaction.
These shells also have commands that are built into the shell and run in the shell process, such as the typeset command in KSH and the dir command in Cmd.exe. In most shells, because there are few built-in commands.many utilities have been created.
Windows PowerShell is very different.
· Windows PowerShell does not process text. Instead, it processes objects based on the .NET platform.
· Windows PowerShell comes with a large set of built-in commands with a consistent interface.
· All shell commands use the same command parser, instead of different parsers for each tool. This makes it much easier to learn how to use each command.
Best of all, you don't have to give up the tools that you have become accustomed to using. You can still use the traditional Windows tools, such as Net, SC, and Reg.exe in Windows PowerShell.
Windows PowerShell Cmdlets
A cmdlet (pronounced "command-let") is a single-feature command that manipulates objects in Windows PowerShell. You can recognize cmdlets by their name format -- a verb and noun separated by a dash (-), such as Get-Help, Get-Process, and Start-Service.
In traditional shells, the commands are executable programs that range from the very simple (such as attrib.exe) to the very complex (such as netsh.exe).
In Windows PowerShell, most cmdlets are very simple, and they are designed to be used in combination with other cmdlets. For example, the "get" cmdlets only retrieve data, the "set" cmdlets only establish or change data, the "format" cmdlets only format data, and the "out" cmdlets only direct the output to a specified destination.
Each cmdlet has a help file that you can access by typing:
get-help <cmdlet-name> -detailed
The detailed view of the cmdlet help file includes a description of the cmdlet, the command syntax, descriptions of the parameters, and example that demonstrate use of the cmdlet.
A New Scripting Language
Windows PowerShell uses its own language, rather than reusing existing an languages, for the following reasons.
· Windows PowerShell needed a language for managing.NET objects,
· The language needed to provide a consistent environment for using cmdlets.
· The language needed to support complex tasks, without making simple tasks more complex.
· The language needed to be consistent with higher-level languages used in .NET programming, such as C#.
Windows Commands and Utilities
You can run Windows command-line programs in Windows PowerShell, and you can start Windows programs that have a graphic user interface, such as Notepad and Calculator, within the shell. You can also capture the text that programs generate and use that text in the ,shell, in much the same way you would in Cmd.exe.
Processing Objects
Although you might not realize it at first. when you work in Windows PowerShell, you are working with .NET objects. As you gain experience, the power of object processing becomes more evident, and you'll find yourself using the objects and even thinking in objects.
Technically, a .NET object is an instance of a .NET class that consists of data and the operations associated with that data. But you can think of an object as a data entity that has properties, which are like characteristics, and methods, which are actions that you can perform on the object.
For example, when you get a service in Windows PowerShell, you are really getting an object that represents the service. When you view information about a service, you are viewing the properties of its service object. And, when you start a service, that is, when you change the Status property of the service to "started," you are using a method of the service object.
All objects of the same type have the same properties and methods, but each instance of an object can have different values for the properties. For example, every service object has a Name and Status property. However, each service can have a different name and a different status.
When you're ready, it's easy to learn about the objects. To find out what type of object a cmdlet is getting, use a pipeline operator (|) to sent the results of a "get" command to the Get-Member command. For example, the following command sends the objects retrieved by a Get-Service command to Get-Member.
get-service | get-member |
Get-Member displays information about the service object, including the typename of the object and a list of its properties and methods.
TypeName: System.ServiceProcess.ServiceController Name MemberType Definition ---- ---------- ---------- Name AliasProperty Name = ServiceName add_Disposed Method System.Void add_Disposed(EventHandler value) Close Method System.Void Close() Continue Method System.Void Continue() ... |
For information about the object class, copy and paste the typename, such as System.ServiceProcess.ServiceController, in MSDN. When you find the class, you can read the MSDN subtopics to learn about the properties and methods of objects based on that class, like the ones in Windows PowerShell.
To find the values of all of the properties of a particular object, use a pipeline operator (|) to send the results of a "get" command to a Format-List or Format-Table command. Use the Property parameter of the format cmdlets with a value of all (*). For example, to find all of the properties of the Schedule service on the system, type:
get-service schedule | format-list -property * |
The following shows an example of the result.
Name : Schedule CanPauseAndContinue : True CanShutdown : True CanStop : True DisplayName : Task Scheduler DependentServices : {} MachineName : . ServiceName : Schedule ServicesDependedOn : {RpcSs} ServiceHandle : SafeServiceHandle Status : Running ServiceType : Win32ShareProcess Site : Container : |
You don't need to understand anything about objects when you are first learning Windows PowerShell, but keep the concept in the back of your mind. You'll soon be able to use the objects to their best advantage.
Object Pipelines
One major advantage of using objects is that it makes it much easier to pipeline command, that is, to pass the output of one command to another command as input. The communication often requires string manipulation to convert output from one format to another and to remove titles and column headings.
Windows PowerShell provides a new interactive model that is based on objects, rather than text. The cmdlet that receives an object can act directly on its properties and methods without any conversion or manipulation. Users can refer to properties and methods of the object by name, rather than calculating the position of the data in the output.
In the following example, the result of an IpConfig command is passed to a Findstr command. The pipeline operator (|) sends the result of the command on its left to the command on its right. In Microsoft® Windows® PowerShell, you don't need to manipulate strings or calculate data offsets.
PS> ipconfig | findstr "Address" IP Address. . . . . . . . . . . . : 172.28.21.5 IP Address. . . . . . . . . . . . : 172.30.160.225 |
An Interactive Environment
Like other shells, Windows PowerShell supports a complete interactive environment. When you type a command at the prompt, the command is processed and the output is displayed in the shell window. You can send the output of a command to a file or printer, or you can use the pipeline operator (|) to send the output to another command.
Support for Scripting
If you run particular commands or command sequences repeatedly, or if you develop a series of commands to perform a complex task, you will want to save your commands in a file and execute the command file, instead of typing commands at the prompt. A file of commands is called a script.
In addition to its interactive interface, Windows PowerShell fully supports scripting. In Windows PowerShell, script files have a .ps1 file name extension. To run a script, type the name of the script at the command prompt. The file name extension is optional.
For example:
c:\test\testscript.ps1 |
or
c:\test\testscript |
You must specify the fully qualified path to the script file, even if the script is in the current directory. To indicate the current directory, type the directory name or use a dot (.) to represent the current directory. For example:
.\testscript.ps1 |
Although scripts are extremely useful -- even essential -- in some enterprises, they can be used to spread malicious code. As a result, the security policy in Windows PowerShell, called an execution policy, lets you determine whether scripts can run and whether they must include a digital signature. To eliminate an obvious risk, none of the execution policies in Windows PowerShell allow you to run a script by double-clicking its icon. For more information, type:
get-help about_signing |
Windows PowerShell also includes a very rich scripting language that allows you to create scripts from the simplest to the very complex. It supports language constructs for looping, conditions, flow-control, and variable assignment.
To start Windows PowerShell from the Start menu, click Start, click All Programs, click Windows PowerShell 1.0, and then click Windows PowerShell.
To start Windows PowerShell from the Run box, click Start, click Run, and type:
powershell |
To start Windows PowerShell from a Command Prompt (cmd.exe) windows, at the command prompt, type:
powershell |
To see the options for starting Windows PowerShell, in a Command Prompt window,
type:
powershell -? |
When Windows PowerShell is open, you can use the Get-Help cmdlet to find help. At the Windows PowerShell command prompt, type:
Using Windows PowerShell
This section explains the basics of using Windows PowerShell. It begins with the Get-Help cmdlet, which displays information about cmdlets and conceptual topics in Windows PowerShell. Then, it describes a few of the basic cmdlets, explains how to use cmdlet parameters, and shows you how to format the output of the cmdlets to get the data that you need in a useful display. The final topics explain how to use aliases to make it easier to work in Windows PowerShell, how to run traditional Windows programs in Windows PowerShell, and how to manage errors.
Get-Help: Getting Help
The Get-Help cmdlet is a useful tool for learning about Windows PowerShell. By reading the descriptions of the cmdlets, learning about the concepts, and exploring the language topics, you can begin to understand how to use Windows PowerShell .
The first topic of interest might be the help system. To display information about the help system in Windows PowerShell, type:
get-help |
Then, you might be interested in learning about a few of the basic cmdlets, such as Get-Help, Get-Command, Get-Process, Get-Service, and Get-Eventlog.
To display the simplest view of a help for a cmdlet, type "get-help" following by the cmdlet name. For example, to get help for the Get-Command cmdlet, type:
get-help get-command |
If the cmdlet help is not formatted correctly, that is, if it begins with XMLNS tags, the Windows PowerShell execution policy on your system might have prevented the system from loading the configuration file that formats cmdlet help. For information about execution policies, type:
get-help about_signing |
To display detailed help for a cmdlet, including parameter descriptions and examples, use the Detailed parameter of Get-Help. For example, to get detailed help for the Get-Command cmdlet, type:
get-help get-command -detailed |
To display all of the available help for a cmdlet, including technical information about the cmdlet and its parameters, use the Full parameter. For example, to get complete help for the Get-Command cmdlet, type:
get-help get-command -full |
You can also display selected parts of the help file. To see only the examples, use the Examples paramter. For example, to display the examples for the Get-Command cmdlet, type:
get-help get-command -examples |
To see only detailed parameter descriptions, use the Parameter parameter of Get-Help. You can specify the name of a parameter or use the wildcard character (*) to specify all parameters. For example, to see a description of the TotalCount parameter of Get-Command, type:
get-help get-command -parameter totalcount |
To see all parameters of the Get-Command cmdlet, type:
get-help get-command -parameter * |
You can also use one of the Windows PowerShell functions that call Get-Help. The Help function displays one screen full of help at a time. The Man function displays help that looks like Man pages in Unix. To use the Help and Man functions to display help for the Get-Command cmdlet, type:
man get-command |
or
help get-command |
When you request a particular help topic, Get-Help displays the content of the topic. But when you use wildcard characters to request more than one topic, Get-Help displays a list of topics. For example, to see a list of help topics for the "Get" cmdlets, type:
get-help get-*
Help about concepts in Windows PowerShell begins with "about_".To display help about a Windows PowerShell concept, type "get-help" followed by the concept name. For example, to get help about wildcards, type:
get-help about_wildcard |
To display a list of all of the conceptual help topics in Windows PowerShell, type:
get-help about_* |
By reading the help topics and trying the examples, you'll get a sense for how Windows PowerShell works and how you can use it in your work.
Using Cmdlets
A cmdlet (pronounced "command-let") is a simple, single-function command-line tool built into the shell. You use cmdlets just as you would use traditional commands and utilities. Begin by typing the name of the cmdlet at the Windows PowerShell command prompt. Windows PowerShell command are not case-sensitive, so you can type in any case.
For example, you can try the Get-Date cmdlet:
C:\PS> get-date Thursday, November 10, 2005 4:43:50 PM |
To list the cmdlets in your session, use the Get-Command cmdlet without any command parameters.
PS> get-command CommandType Name Definition ----------- ---- ---------- Cmdlet Add-Content Add-Content [-Path] <String[... Cmdlet Add-History Add-History [[-InputObject] ... Cmdlet Add-Member Add-Member [-MemberType] <PS... ... … |
The default Get-Command display has three columns: CommandType, Name, and Definition. When listing cmdlets, the Definition column displays the syntax of the cmdlet. The ellipsis in the syntax (…) indicates that the data is truncated.
The Get-Command cmdlet also gets commands and command elements other than cmdlets, including aliases (command nicknames), functions, and executable files that are available in Windows PowerShell.
The following command lists the executable files available in Windows PowerShell by using the Name parameter to Get-Command.
PS> get-command *.exe CommandType Name Definition ----------- ---- ---------- Application 000StTHK.exe C:\WINDOWS\system32\000StTHK.exe Application 00THotkey.exe C:\WINDOWS\system32\00THotkey.exe Application accwiz.exe C:\WINDOWS\system32\accwiz.exe ... |
When listing executable files, the Definition column contains the full path to the executable file.
Then, try some of the other cmdlets, like Get-Process, Get-Service, Get-EventLog, and Get-Alias.
When you feel comfortable with the simple "Get-" cmdlets, try a more interesting one, such as Get-WmiObject. This cmdlet is extremely useful because it lets you view and change the components of remote computers. For example, the following command gets information about the BIOS on the Server01 remote computer:
get-wmiobject win32_bios -computername server01 |
If you need help with any cmdlet, type:
get-help <cmdlet-name> -detailed
for example:
get-help get-alias -detailed.
Learning About Objects: Get-Member
One of the most useful cmdlets is Get-Member, which displays information about the .NET object that a command returns. The information includes the type, properties and methods of the object.
To use Get-Member, use a pipeline operator (|) to send the results of a command to Get-Member. For example:
get-service | get-member
This command reveals that Get-Service actually returns a set of System.ServiceProcess.ServiceController objects -- one for each service on the computer.
TypeName: System.ServiceProcess.ServiceController Name MemberType Definition ---- ---------- ---------- Name AliasProperty Name = ServiceName add_Disposed Method System.Void add_Disposed(EventHandler value) Close Method System.Void Close() Continue Method System.Void Continue() CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType) Dispose Method System.Void Dispose() Equals Method System.Boolean Equals(Object obj) ExecuteCommand Method System.Void ExecuteCommand(Int32 command) get_CanPauseAndContinue Method System.Boolean get_CanPauseAndContinue() get_CanShutdown Method System.Boolean get_CanShutdown() get_CanStop Method System.Boolean get_CanStop() get_Container Method System.ComponentModel.IContainer get_Container() get_DependentServices Method System.ServiceProcess.ServiceController[] get_DependentServices() get_DisplayName Method System.String get_DisplayName() get_MachineName Method System.String get_MachineName() get_ServiceHandle Method System.Runtime.InteropServices.SafeHandle get_ServiceHandle() get_ServiceName Method System.String get_ServiceName() get_ServicesDependedOn Method System.ServiceProcess.ServiceController[] get_ServicesDependedOn() get_ServiceType Method System.ServiceProcess.ServiceType get_ServiceType() get_Site Method System.ComponentModel.ISite get_Site() get_Status Method System.ServiceProcess.ServiceControllerStatus get_Status() GetHashCode Method System.Int32 GetHashCode() GetLifetimeService Method System.Object GetLifetimeService() GetType Method System.Type GetType() InitializeLifetimeService Method System.Object InitializeLifetimeService() Pause Method System.Void Pause() Refresh Method System.Void Refresh() remove_Disposed Method System.Void remove_Disposed(EventHandler value) set_DisplayName Method System.Void set_DisplayName(String value) set_MachineName Method System.Void set_MachineName(String value) set_ServiceName Method System.Void set_ServiceName(String value) set_Site Method System.Void set_Site(ISite value) Start Method System.Void Start(), System.Void Start(String[] args) Stop Method System.Void Stop() ToString Method System.String ToString() WaitForStatus Method System.Void WaitForStatus(ServiceControllerStatus desiredStatus), System.Voi... CanPauseAndContinue Property System.Boolean CanPauseAndContinue {get;} CanShutdown Property System.Boolean CanShutdown {get;} CanStop Property System.Boolean CanStop {get;} Container Property System.ComponentModel.IContainer Container {get;} DependentServices Property System.ServiceProcess.ServiceController[] DependentServices {get;} DisplayName Property System.String DisplayName {get;set;} MachineName Property System.String MachineName {get;set;} ServiceHandle Property System.Runtime.InteropServices.SafeHandle ServiceHandle {get;} ServiceName Property System.String ServiceName {get;set;} ServicesDependedOn Property System.ServiceProcess.ServiceController[] ServicesDependedOn {get;} ServiceType Property System.ServiceProcess.ServiceType ServiceType {get;} Site Property System.ComponentModel.ISite Site {get;set;} Status Property System.ServiceProcess.ServiceControllerStatus Status {get;} |
This information looks very technical, but it is actually very practical.
· The typename (such as "System.ServiceProcess.ServiceController") tells you what type of .NET object the cmdlet returns. For information about objects in this .NET class, paste the typename in the Search text box in MSDN. The associated MSDN topic includes information about the properties and methods of objects in this class, including the objects that Get-Service returns.
· The Property types represent properties of the objects. The value of each property is information about the service object. For example, the ServiceController objects have a CanPauseAndContinue property. The MSDN description of the property explains that the property tells whether the service can be paused and resumed.
To list the value of a property of a particular service, type:
(get-service <service-name>).<property-name> |
such as:
(get-service alerter).canpauseandcontinue |
To display a list with the name and the value of the CanPauseAndContinue property of the Alerter service, type:
get-service alerter | format-list -property name, CanPauseAndContinue |
To display a list of the values of all properties of the Alerter service, type:
get-service alerter | format-list -property * |
To display a table with the name and the value of the CanPauseAndContinue property of all services, type:
get-service | format-table -property name, CanPauseAndContinue |
· The Method types represent methods of the object, that is, actions that you can perform on the object. For example, ServiceController objects have a Stop method that lets you stop the service.
To call a method of a service object, use the following format. (Be sure to include the parentheses).
(get-service <service-name>).<method-name>() For example, (get-service schedule).stop() |
For information about the Get-Member command, type:
get-help get-member -detailed.
Using Cmdlet Parameters
Cmdlet parameters are identified by a hyphen (-) preceding the parameter name. (Slashes (/ and \) are not used with parameters in Windows PowerShell.)
When you type a parameter name, you can type the whole name, but you only need to type enough characters to distinguish the parameter name from the names other parameters of the cmdlet.
For example, the Get-Help cmdlet has a parameter named "Detailed," but you can type "-det", which is just enough to distinguish it from the Debug parameter of Get-Help.
Some parameter names are optional. You can use the parameter by typing a parameter value without typing the parameter name. However, if you omit the parameter name, the parameter value must appear in the in the same position in the command that it appears in the syntax diagram.
For example, the Get-Help cmdlet has a Name parameter that specifies the name of a cmdlet or concept. You can type the name of the Name parameter or leave it out. To get help for the Get-Alias command, you can type:
get-help -name get-alias |
or
get-help get-alias |
To find the optional parameter names, see the syntax block in the help file. Optional parameter names appear in square brackets, such as:
Get-Help [[-Name] <string>]... |
Common Parameters
All cmdlets support a set of parameters that are called common parameters. This feature provides a consistent interface to Windows PowerShell.
When a cmdlet supports a common parameter, the use of the parameter does not cause an error. However, the parameter might not have any effect in some cmdlets. For a description of the common parameters, type:
get-help about_commonparameters
Formatting Command Output
In traditional shells, each tool or command determines the format of its output. Some tools let you customize the output, and they include special parameters to control the output format.
In Windows PowerShell, the only cmdlets that format output are the format cmdlets:
· Format-List
· Format-Custom
· Format-Table
· Format-Wide
None of the other cmdlets format output. As a result, you don't need to learn the formatting routines and parameters of multiple tools. Just learn about the Format cmdlets and their parameters.
When you run a command, the Windows PowerShell calls the default formatter, which is determined by the type of data being displayed. The formatter determines which properties of the output are displayed and whether they are displayed in a list or table.
For example, when you use the Get-Service cmdlet, the default display is a three-column table, such as the following:
C:\PS> get-service Status Name DisplayName ------ ---- ----------- Running AdtAgent Event Forwarder Stopped Alerter Alerter Running ALG Application Layer Gateway Service |
...
To change the format of the output from any cmdlet, use the pipeline operator (|) to send the output of the command to a Format cmdlet.
For example, the following command sends the output of a Get-Service command to the Format-List cmdlet. As a result, the service data is formatted as a list for each service.
C:\PS> get-service | format-list Name : AdtAgent DisplayName : Event Forwarder Status : Running DependentServices : {} ServicesDependedOn : {eventlog, dnscache} CanPauseAndContinue : False CanShutdown : True CanStop : True ServiceType : Win32OwnProcess Name : Alerter DisplayName : Alerter Status : Stopped DependentServices : {} ServicesDependedOn : {LanmanWorkstation} CanPauseAndContinue : False CanShutdown : False CanStop : False ServiceType : Win32ShareProcess Name : ALG DisplayName : Application Layer Gateway Service Status : Running DependentServices : {} |
In this format, not only does the data appear in a list, instead of a table, but there is more information about each service. Instead of three columns of data for each service, there are nine rows of data. Format-List did not retrieve the extra service information. The data was there all along in the objects that Get-Service retrieved, but Format-Table, the default formatter, omitted it, because it could not display more than three columns across on the screen.
In addition to determining whether the data appears in a list or table, you can also determine which properties of the object are displayed. For example, the default display of Get-Service display only the Status, Name, and DisplayName properties of the service object.
To see all of the properties of an object, use a pipeline operator (|) to send the output of a command to the Get-Member cmdlet. For example, to see all of the properties of a service object, type:
get-service | get-member -membertype *property TypeName: System.ServiceProcess.ServiceController Name MemberType Definition ---- ---------- ---------- Name AliasProperty Name = ServiceName CanPauseAndContinue Property System.Boolean CanPauseAndContinue {get;} CanShutdown Property System.Boolean CanShutdown {get;} CanStop Property System.Boolean CanStop {get;} Container Property System.ComponentModel.IContainer Container {get;} DependentServices Property System.ServiceProcess.ServiceController[] DependentServices {get;} DisplayName Property System.String DisplayName {get;set;} MachineName Property System.String MachineName {get;set;} ServiceHandle Property System.Runtime.InteropServices.SafeHandle ServiceHandle {get;} ServiceName Property System.String ServiceName {get;set;} ServicesDependedOn Property System.ServiceProcess.ServiceController[] ServicesDependedOn {get;} ServiceType Property System.ServiceProcess.ServiceType ServiceType {get;} Site Property System.ComponentModel.ISite Site {get;set;} Status Property System.ServiceProcess.ServiceControllerStatus Status {get;} |
Because all of these properties are in the object that Get-Service retrieves for each service, you can display any or all of them. Use the Property parameter of the Format cmdlets to select the properties to be displayed and the other in which they are displayed. For example, the following command uses the Format-Table command to display only the Name, ServiceType, and CanShutDown properties of the service.
get-service | format-table name, Servicetype, Canshutdown |
This is just the beginning of what you can do with Windows PowerShell displays. For more details, use the following commands to read the help for the Format cmdlets:
get-help format-list get-help format-table get-help format-wide get-help format-custom |
Using Aliases
Cmdlet names can be cumbersome to type. To minimize typing, and to make it easier for users accustomed to other shells to use Windows PowerShell, Windows PowerShell supports the concept of an alias, that is, an alternate name for a command. You can create an alias for a cmdlet name, function name, or the name of an executable file, and then type the alias instead of the name in any command.
Windows PowerShell includes many built-in aliases and you can create your own. The aliases that you create are valid only within the current session. To create a persistent alias, add the alias to your Windows PowerShell profile.
To find all of the aliases in your session, type:
get-alias |
To find the aliases for a cmdlet, type:
get-alias | where-object {$_.definition -eq "<cmdlet-name>"} |
For example:
get-alias | where-object {$_.definition -eq "set-location"} |
The aliases in Windows PowerShell are supported by the Windows PowerShell Alias provider, a .NET assembly that lets you view the aliases in a drive that looks much like the file system drives in Windows. The drive for aliases is Alias:.
To change to the Alias drive, type:
set-location alias: |
To view the aliases, that is, the child items in the Alias: drive, type
get-childitem |
To view the child items in the Alias: drive from another drive, include the drive name in the command. For example:
get-childitem alias: |
Creating an alias
To create aliases for cmdlets and commands in Windows PowerShell, use the Set-Alias cmdlet. For example, to create the "gh" alias for the Get-Help cmdlet, type:
set-alias gh get-help |
You can also create aliases for commands, such as the commands that start a program. For example, to create the alias "np" for Notepad, type:
set-alias np c:\windows\notepad.exe |
(The path to Notepad might be different on your system.)
Deleting an alias
To delete an alias, use the Remove-Item cmdlet to delete the alias from the Alias: drive. For example, to remove the "ls" alias, type
remove-item alias:ls |
Using Functions to Create Alternate Names
You can create an alias for a cmdlet, function, or executable file, but you cannot create an alias for a command with parameters. You can, however, create a function that behaves much like an alias.
For example, to use Notepad to open the Boot.ini file on a computer running Windows XP, type:
notepad c:\boot.ini |
You cannot create an alias for "notepad c:\boot.ini", but you can create a function. The following command creates the bootini function.
function bootini {notepad c:\boot.ini} |
This function behaves like an alias. If you type bootini at the Windows PowerShell prompt, Boot.ini opens in Notepad.
Using Windows Programs
You can run Windows command-line programs and start Windows graphic programs in Windows PowerShell. If the program generates text outpu, you can capture the text and use it in the new shell, just as you would in any shell.
To run a program, such as Notepad, in Windows PowerShell, the executable file for the program must be located in a directory that is included in the Path environment variable, because the value of the Path environment variable determines where Windows PowerShell looks for applications, utilities, and scripts. (Cmdlets do not have to be in a Path directory.)
To see the paths in the Path environment variable, type:
PS> $env:path |
To add directories to the Path environmnet variable, type:
PS> $env:path += ";newdirectory" |
For example, to add the directory of the WordPad.exe file to the Path variable, type:
PS> $env:path += ";C:\Program Files\Windows NT\Accessories" |
Like the set command, this assignment statement only changes the value of Path for the current Windows PowerShell session. To make the change permanent, add the assignment statement to your Windows PowerShell profile. For details, see the "Windows PowerShell Profiles" topic.
Managing Errors
Errors will occur occasionally when you use the shell, such as when you are trying to set your location to a nonexistent directory or trying to remove a file without the required privileges.
In Windows PowerShell, there are two types of errors:
· Terminating errors: Errors that halt the execution of the command.
· Non-terminating errors: Errors that do not halt the execution of the command.
For example, if you are removing all of the .TMP files from a directory, you might not want the operation to stop if one of the files cannot be removed. Typically, you want to remove all of the files that you can remove, and then go back for the files that you could not remove.
The error that occurs when you cannot remove a file is called a non-terminating error. When a non-terminating error occurs, Windows PowerShell continues despite the error and then displays the error along with the output.
More serious errors will stop command processing. These are called terminating errors. Terminating errors stop the processing of the command. For example, if you submit invalid data or you don't have the permissions required to perform the command, Windows PowerShell generates a non-terminating error.
One of the most powerful features of Windows PowerShell is that it lets you navigate through many different data stores by using the same familiar techniques that you use to navigate in the file system.
In addition to the familiar file system drives, such as C: and D:, Windows PowerShell includes drives that represent the HKEY_LOCAL_MACHINE (HKLM:) and HKEY_CURRENT_USER (HKCU:) registry hives, the digital signature certificate store on your computer (Cert:), and the functions in the current session (Function:), among others. These are known as Windows PowerShell drives.
Windows PowerShell comes with several useful drives which are supported by Windows PowerShell providers. To see a list of Windows PowerShell drives, type:
get-psdrive |
Navigating the File System
When you start Windows PowerShell, you might be tempted to type the familiar cd, dir or ls. Do it! cd is an alias for the Set-Location cmdlet, the cmdlet that changes the current location to the specified path. dir and ls are aliases for the Get-Childitem cmdlet, the cmdlet that gets the child items in a location.
To navigate within the file system drive, use the Set-Location (cd) and Get-Childitem (dir, ls) cmdlets. In Windows PowerShell, drives are indicated by the drive name followed by a colon (:), such as C:, and parent items are separated from child item by backslashes (\) or forward slashes (/), such as C:\Windows\System32.
There are a few features that make it easier to navigate in Windows PowerShell:
· There are symbols for the current directory (.) and the contents of a directory (*).
· There are built-in variables for your home directory, $home, and the Windows PowerShell installation directory, $pshome.
As in other shells, you can change locations, create, delete, move, and copy directories and files, and change their properties. You can even use tab-completion for path names. For details, see help for the Item cmdlets (Get-Item, Get-Childitem, New-Item, Remove-Item, Set-Item, Move-Item, and Copy-Item).
Navigating the Registry
You can navigate through the Windows registry by using the same techniques that you use to navigate in the file system drive. In Windows PowerShell, the HKEY_LOCAL_MACHINE hive maps to the Windows PowerShell HKLM: drive and the HKEY_CURRENT_USER drive maps to the Windows PowerShell HKCU: drive.
For example:
PS C:\> cd hklm: PS HKLM:\> dir PS HKLM:\> dir Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE SKC VC Name Property --- -- ---- -------- 4 0 HARDWARE {} 1 0 SAM {} Get-ChildItem : Requested registry access is not allowed. At line:1 char:3 + dir <<<< 39 2 SOFTWARE {flash, (default)} 8 0 SYSTEM {} PS HKLM:\> cd system\currentcontrolset\control PS HKLM:\system\currentcontrolset\control> dir |
As you navigate, you will notice that the output of dir (Get-Childitem) is different in the registry drives than it is in the file system. Because the registry has different drives with different information, the shell provides a different view of the data. In this case, it is important to know how many subkeys and entries are present, so the output includes a subkey count (SKC) and a value entry count (VC), in addition to the names of the subkeys and the entries.
PS> cd "CurrentControlSet\Control\Session Manager" PS> dir Hive: Registry::HKEY_LOCAL_MACHINE\system\CurrentControlSet\Control\Session Manager SKC VC ChildName Property --- -- --------- -------- 0 1 AppCompatibility {AppCompatCache} 15 0 AppPatches {} 0 7 DOS Devices {AUX, MAILSLOT, NUL, PIPE, PRN, UNC, f... |
You won't encounter very many differences in navigation until you get to the registry entries. The entries in a registry key are considered to be properties of the key in which they are located. As such, you use the Get-ItemProperty cmdlet to retrieve them.
For example, if you want to see the value of the Windows PowerShell execution policy, you can use the Get-ExecutionPolicy cmdlet or navigate to the ExecutionPolicy registry entry that stores the value in HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell.
PS C:\> cd hklm: PS HKLM:\> cd software\microsoft\powershell\1\ShellIds\Microsoft.PowerShell PS HKLM:\software\microsoft\powershell\1\ShellIds\Microsoft.PowerShell> dir PS HKLM:\software\microsoft\powershell\1\ShellIds\Microsoft.PowerShell> get-itemproperty -path . -name executionpolicy PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\microsoft\powershell\1\ShellIds\Micro soft.PowerShell PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\microsoft\powershell\1\ShellIds PSChildName : Microsoft.PowerShell PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry ExecutionPolicy : RemoteSigned |
Navigating the Certificate Store
You can navigate in the digital signature certificate store on your computer, too. The certificate store maps to theWindows PowerShell Cert: drive. The following example shows how to use Set-Location (cd) and Get-Childitem (dir, ls) to navigate the Cert: drive.
PS C:\> cd cert: PS cert:\> dir Location : CurrentUser StoreNames : {TrustedPeople, _NMSTR, Trust, REQUEST...} Location : LocalMachine StoreNames : {_NMSTR, Trust, REQUEST, TrustedPeople...} PS cert:\> cd currentuser PS cert:\currentuser> dir Name : TrustedPeople Name : _NMSTR Name : Trust Name : REQUEST Name : AuthRoot Name : ACRS Name : My Name : addressbook Name : Disallowed Name : CA Name : UserDS Name : Root Name : TrustedPublisher PS cert:\currentuser> cd authroot PS cert:\currentuser\authroot> dir Directory: Microsoft.PowerShell.Security\Certificate::currentuser\authroot Thumbprint Subject ---------- ------- F88015D3F98479E1DA553D24FD42BA3F43886AEF O=C&W HKT SecureNet CA SGC Root, C=hk F44095C238AC73FC4F77BF8F98DF70F8F091BC52 CN=Class 3TS Primary CA, O=Certplus, C=FR EF2DACCBEABB682D32CE4ABD6CB90025236C07BC O="Colegio Nacional de Correduria Publica Mexicana, A.C.", CN="Autoridad C... ... PS cert:\currentuser\authroot> get-childitem F88015D3F98479E1DA553D24FD42BA3F43886AEF Directory: Microsoft.PowerShell.Security\Certificate::currentuser\authroot Thumbprint Subject ---------- ------- F88015D3F98479E1DA553D24FD42BA3F43886AEF O=C&W HKT SecureNet CA SGC Root, C=hk PS cert:\currentuser\authroot> get-childitem F88015D3F98479E1DA553D24FD42BA3F43886AEF | format-list -property * PSPath : Microsoft.PowerShell.Security\Certificate::currentuser\authroot\F88015D3F98479E1DA553D24FD42BA3F43 886AEF PSParentPath : Microsoft.PowerShell.Security\Certificate::currentuser\authroot PSChildName : F88015D3F98479E1DA553D24FD42BA3F43886AEF PSDrive : cert PSProvider : Microsoft.PowerShell.Security\Certificate PSIsContainer : False Archived : False Extensions : {} FriendlyName : CW HKT SecureNet CA SGC Root IssuerName : System.Security.Cryptography.X509Certificates.X500DistinguishedName NotAfter : 10/16/2009 2:59:00 AM NotBefore : 6/30/1999 3:00:00 AM HasPrivateKey : False PrivateKey : PublicKey : System.Security.Cryptography.X509Certificates.PublicKey RawData : {48, 130, 2, 235...} SerialNumber : 00 SubjectName : System.Security.Cryptography.X509Certificates.X500DistinguishedName SignatureAlgorithm : System.Security.Cryptography.Oid Thumbprint : F88015D3F98479E1DA553D24FD42BA3F43886AEF Version : 1 Handle : 1577256 Issuer : O=C&W HKT SecureNet CA SGC Root, C=hk Subject : O=C&W HKT SecureNet CA SGC Root, C=hk |
Navigating Other Drives
In addition to the file system, registry, and certificate drives, Windows PowerShell comes several other useful drives, including the alias (Alias:), environment provider (Env:), function (Function:), and variable (Variable:) drives. You use the basic same techniques to navigate in these drives.
About Windows PowerShell Drives
The concept behind the expanded navigation features in Windows PowerShell is the Windows PowerShell drive.
Windows PowerShell drives can be created in any data store that is available in Windows PowerShell, and they can have any valid name, such as C: or "My Drive", followed by a colon (:). You can navigate in them by using that same methods that you would use in a file system drive. However, the Windows PowerShell drives are visible only in Windows PowerShell. You cannot see them or gain access to them in Windows Explorer or Cmd.exe.
Windows PowerShell comes with several useful drives which are supported by Windows PowerShell providers. To see a list of Windows PowerShell drives, type:
get-psdrive |
You can also create your own Windows PowerShell drives by using the New-PsDrive cmdlet. For example, to create a new drive called "MyDocs:" that is rooted in your My Documents directory, type:
new-psdrive -name MyDocs -psprovider FileSystem -root "$home\My Documents" |
You can now use the MyDocs: drive as you would any other drive. You can change your location to it, enumerate its contents, and change its properties.
Drives and Providers
The drives in Windows PowerShell are made available to your session by Windows PowerShell providers, which are .NET assemblies that make the data in a specialized data store available in Windows PowerShell so that you can easily view and manage the data. For information about Windows PowerShell providers, type:
get-help about_psprovider |
To see a list of Windows PowerShell providers, type:
get-psprovider |
For a list of provider help files, type:
get-help -category provider |
For information about a particular provider, type:
get-help <provider-name> |
For example,
get-help registry |
This section describes a few of the ways that you can customize Windows PowerShell to best meet your needs.
Examine the Execution Policy
Scripting is a very powerful tool, but it can be misued for malicious purposes. To protect user data and the integrity of the operating system, Windows PowerShell includes several security features, among which is the execution policy.
The Windows PowerShell execution policy determines whether scripts are allowed to run and, if they can run, whether they must be digitally signed. It also determines whether configuration files can be loaded.
The default execution policy, Restricted, is the most secure of the execution policies. It does not permit any scripts to run, and it does not permit any configuration files, including a Windows PowerShell profile, to be loaded. You can still use Windows PowerShell interactively.
However, if you want to run scripts or load configuration files, you can change the execution policy on your system. For information and instructions, type:
get-help about_signing |
To find the execution policy on your system, type:
get-executionpolicy |
To change the execution policy on your system, use the Set-ExecutionPolicy cmdlet. For example, to change the execution policy to RemoteSigned, type:
set-executionpolicy remotesigned |
The Windows PowerShell execution policy is saved in the Windows registry and is retained even when you uninstall and reinstall Windows PowerShell.
Windows PowerShell Profiles
When you add aliases, functions, and variables to Windows PowerShell, you are actually adding them only to the current Windows PowerShell session. If you exit the session or close Windows PowerShell, the changes are lost.
To retain these changes, you can create a Windows PowerShell profile and add the aliases, functions, and variables to the profiles. The profile is loaded every time that Windows PowerShell starts.
To load a profile, your Windows PowerShell execution policy must permit you to load configuration files. If it does not, the attempt to load the profile fails and Windows PowerShell displays an error message.
Understanding the Profiles
You can have four different profiles in Windows PowerShell. The profiles are listed in load order. The most specific profiles have precedence over less specific profiles where they apply.
· %windir%\system32\WindowsPowerShell\v1.0\profile.ps1
This profile applies to all users and all shells.
· %windir%\system32\WindowsPowerShell\v1.0\ Microsoft.PowerShell_profile.ps1
This profile applies to all users, but only to the Microsoft.PowerShell shell.
· %UserProfile%\My Documents\WindowsPowerShell\profile.ps1
This profile applies only to the to the current user, but affects all shells.
· %UserProfile%\\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
This profile applies only to the current user and the Microsoft.PowerShell shell.
Creating a Profile
You can create, share, and distribute profiles to enforce a consistent view of Windows PowerShell in a larger enterprise.
The profiles are not created automatically. To create a profile, create a text file with the specified name in the specified location.
Typically, you will use the user-specific, shell-specific profile, known as the user profile. The location of this profile is stored in the $profile variable.
To determine if the user profile has been created , type:
test-path $profile |
If the profile exists, the response is True; otherwise, it is False.
To create a user profile, type:
new-item -path $profile -itemtype file -force |
To open the profile in Notepad, type:
notepad $profile |
To create one of the other profiles, such as the profile that applies to all users and all shells, type:
new-item -path C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 -itemtype file -force |
You cannot use the "%" notation for environment variables in Windows PowerShell. To identify a Windows environment variable, use the format: $env:<variable>, such as $env:windir:
new-item -path C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 -itemtype file -force |
If you create a profile in Notepad and then save it, be sure to enclose the file name in quotation marks. For example:
"profile.ps1" |
Without the quotation marks, Notepad appends the .txt file name extension to the file, and Windows PowerShell will not recognize it.
Use the profile to store the aliases, functions, and variables that you routinely. One very useful function is a function that opens the profile in your favorite text editor. For example, the following command creates a function called pro that opens the user profile in Notepad.
function pro { notepad $profile } |
A well-designed profile can make it even easier to use Windows PowerShell and to administer your system.