FANDOM


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.



Windows PowerShell

Getting Started Guide

Copyright


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 Design Goals

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.

Introducing Windows PowerShell

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


Interaction and Scripting

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.

Starting Windows PowerShell

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:

get-help

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.

Navigating Windows PowerShell

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


Customizing Windows PowerShell

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.


Suleras:Infobox software Suleras:Infobox programming language Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework. PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems. In PowerShell, administrative tasks are generally performed by cmdlets (pronounced command-lets), specialized .NET classes implementing a particular operation. Sets of cmdlets may be combined together in scripts, executables (which are standalone applications), or by instantiating regular .NET classes (or WMI/COM Objects).[1][2] These work by accessing data in different data stores, like the filesystem or registry, which are made available to the PowerShell runtime via Windows PowerShell providers. Windows PowerShell also provides a hosting mechanism with which the Windows PowerShell runtime can be embedded inside other applications. These applications then leverage Windows PowerShell functionality to implement certain operations, including those exposed via the graphical interface. This capability has been utilized by Microsoft Exchange Server 2007[1][3] to expose its management functionality as PowerShell cmdlets and providers and implement the graphical management tools as PowerShell hosts which invoke the necessary cmdlets. Other Microsoft applications including Microsoft SQL Server 2008[4] also expose their management interface via PowerShell cmdlets. With PowerShell, graphical interface-based management applications on Windows are layered on top of Windows PowerShell. A PowerShell scripting interface for Windows products is mandated by the Common Engineering Criteria.[5] Windows PowerShell includes its own extensive, console-based help, similar to man pages in Unix shells via the Get-Help cmdlet.

BackgroundEdit

Every released version of Microsoft DOS and Microsoft Windows for personal computers has included a command-line interface tool (shell). These are COMMAND.COM (in installations relying on MS-DOS, including Windows 9x) and cmd.exe (in Windows NT family operating systems). The shell is a command line interpreter that support a few basic commands. For other purposes, a separate console application must be invoked from the shell. The shell also includes a scripting language (batch files), which can be used to automate various tasks. However, the shell cannot be used to automate all facets of GUI functionality, in part because command-line equivalents of operations exposed via the graphical interface are limited, and the scripting language is elementary and does not allow the creation of complex scripts. In Windows Server 2003, the situation was improved,[6] but scripting support was still considered unsatisfactory.

Microsoft attempted to address some of these shortcomings by introducing the Windows Script Host in 1998 with Windows 98, and its command-line based host: cscript.exe. It integrates with the Active Script engine and allows scripts to be written in compatible languages, such as JScript and VBScript, leveraging the APIs exposed by applications via COM. However, it too has its own deficiencies: it is not integrated with the shell, its documentation is not very accessible, and it quickly gained a reputation as a system vulnerability vector after several high-profile computer viruses exploited weaknesses in its security provisions. Different versions of Windows provided various special-purpose command line interpreters (such as netsh and WMIC) with their own command sets. None of them were integrated with the command shell; nor were they interoperable.

By 2002 Microsoft had started to develop a new approach to command line management, including a shell called Monad (aka Microsoft Shell or MSH). The shell and the ideas behind it were published in August 2002 in a white paper entitled Monad Manifesto.[7] Monad was to be a new extensible command shell with a fresh design that would be capable of automating a full range of core administrative tasks. Microsoft first showed off Monad at the Professional Development Conference in Los Angeles in September 2003. A private beta program began a few months later which eventually led to a public beta program.

Microsoft published the first Monad public beta release on June 17, 2005, Beta 2 on September 11, 2005, and Beta 3 on January 10, 2006. Not much later, on April 25, 2006 Microsoft formally announced that Monad had been renamed Windows PowerShell, positioning it as a significant part of their management technology offerings.[8] Release Candidate 1 of PowerShell was released at the same time. A significant aspect of both the name change and the RC was that this was now a component of Windows, and not an add-on product.

Release Candidate 2 of PowerShell version 1 was released on September 26, 2006 with final Release to the web (RTW) on November 14, 2006 and announced at TechEd Barcelona. PowerShell for earlier versions of Windows was released on January 30, 2007.[9]

PowerShell v2.0 development began when PowerShell v1.0 shipped. There were three community technology preview (CTP) releases that Microsoft made available to the public. The last CTP release of Windows PowerShell v2.0 was made available in December 2008.

PowerShell v2.0 was completed and released to manufacturing in August 2009, as an integral part of Windows 7 and Windows Server 2008 R2. Versions of PowerShell for Windows XP, Windows Server 2003, Windows Vista and Windows Server 2008 were released in October 2009 and are available for download for both 32-bit and 64-bit platforms.[10]

OverviewEdit

There are four kinds of commands Windows PowerShell can execute:

  • cmdlets, which are .NET programs designed to interact with PowerShell
  • PowerShell scripts (files suffixed by .ps1)
  • PowerShell functions
  • standalone executable programs

If a command is a standalone executable program, PowerShell.exe launches it in a separate process; if it is a cmdlet, it is executed in the PowerShell process. PowerShell also provides an interactive command line interface, wherein the commands can be entered and their output displayed. The user interface, based on the Win32 console, offers customizable tab completion but lacks syntax highlighting. PowerShell also enables the creation of aliases for cmdlets, which are textually translated by PowerShell into invocations of the original commands. PowerShell also supports both named and positional parameters for commands. In executing a cmdlet, the job of binding the argument value to the parameter is done by PowerShell itself, but, for external executables, arguments are passed via the argv (or equivalent) variable array to be parsed by the executable.

Another concept used by PowerShell is that of a pipeline. Like Unix pipelines, PowerShell pipelines are used to compose complex commands, allowing the output of one command to be passed as input to another, using the | operator. But unlike its Unix counterpart, the PowerShell pipeline is an object pipeline; that is, the data passed between cmdlets are fully typed objects, rather than character streams. When data is piped as objects, the elements they encapsulate retain their structure and types across cmdlets, without the need for any serialization or explicit parsing of the stream, as would be the need if only character streams were shared. An object can also encapsulate certain functions that work on the contained data. These also become available to the recipient command for use.[11][12] For the last cmdlet in a pipeline, PowerShell automatically pipes its output object to the Out-Default cmdlet, which transforms the objects into a stream of format objects and then renders those to the screen.[13][14]

Because all PowerShell objects are .NET objects, they share a .ToString() method, which retrieves the text representation of the data in an object. Windows PowerShell uses this method to convert an object to text. In addition, it also allows formatting definitions to be specified, so the text representation of objects may be customized by choosing which data elements to display, and how. However, in order to maintain backwards compatibility, if an external executable is used in a pipeline, it receives a text stream representing the object, and does not integrate with the PowerShell type system.

The PowerShell Extended Type System (ETS) is based on the .NET type system, but with extended semantics (e.g. propertySets and 3rd party extensibility) . For example, it enables the creation of different views of objects by exposing only a subset of the data fields, properties, and methods, as well as specifying custom formatting and sorting behavior. These views are mapped to the original object using XML-based configuration files.[15]

CmdletsEdit

Cmdlets are specialized commands in the PowerShell environment that implement specific functions. These are the native commands in the PowerShell stack. Cmdlets follow a <verb>-<noun> naming pattern, such as Get-ChildItem, helping to make them self-descriptive.[16] Cmdlets output their results as objects, or collections thereof (including arrays), and can optionally receive input in that form, making them suitable for use as recipients in a pipeline. But, whereas PowerShell allows arrays and other collections of objects to be written to the pipeline, cmdlets always process objects individually. For collections of objects, PowerShell invokes the cmdlet on each object in the collection, in sequence.[16]

Cmdlets are specialized .NET classes, which the PowerShell runtime instantiates and invokes when they are run. Cmdlets derive either from Cmdlet or from PSCmdlet, the latter being used when the cmdlet needs to interact with the PowerShell runtime.[16] These base classes specify certain methods - BeginProcessing()<code>, <code>ProcessRecord() and EndProcessing() - which the cmdlet's implementation overrides to provide the functionality. Whenever a cmdlet is run, these methods are invoked by PowerShell in sequence, with ProcessRecord() being called if it receives pipeline input.[17] If a collection of objects is piped, the method is invoked for each object in the collection. The class implementing the Cmdlet must have one .NET attribute - CmdletAttribute - which specifies the verb and the noun that make up the name of the cmdlet. Common verbs are provided as an enum.

If a cmdlet receives either pipeline input or command-line parameter input, there must be a corresponding property in the class, with a mutator implementation. PowerShell invokes the mutator with the parameter value or pipeline input, which is saved by the mutator implementation in class variables. These values are then referred to by the methods which implement the functionality. Properties that map to command-line parameters are marked by ParameterAttribute[18] and are set before the call to BeginProcessing(). Those which map to pipeline input are also flanked by ParameterAttribute, but with the ValueFromPipeline attribute parameter set.[19]

The implementation of these cmdlet classes can refer to any .NET API and may be in any .NET language. In addition, PowerShell makes certain APIs available, such as WriteObject(), which is used to access PowerShell-specific functionality, such as writing resultant objects to the pipeline. Cmdlets can use .NET data access APIs directly or use the PowerShell infrastructure of PowerShell Providers, which make data stores addressable using unique paths. Data stores are exposed using drive letters, and hierarchies within them, addressed as directories. Windows PowerShell ships with providers for the file system, registry, the certificate store, as well as the namespaces for command aliases, variables, and functions.[20] Windows PowerShell also includes various cmdlets for managing various Windows systems, including the file system, or using Windows Management Instrumentation to control Windows components. Other applications can register cmdlets with PowerShell, thus allowing it to manage them, and, if they enclose any datastore (such as databases), they can add specific providers as well.

In PowerShell V2, a more portable version of Cmdlets called Modules have been added. The PowerShell V2 release notes state, "Modules allow script developers and administrators to partition and organize their Windows PowerShell code in self-contained, reusable units. Code from a module executes in its own self-contained context and does not affect the state outside of the module. Modules also enable you to define a restricted runspace environment by using a script."

PipelineEdit

PowerShell, like Unix/Linux based shells, implements a pipeline. This pipeline enables the output of one cmdlet to be piped as input to another cmdlet. For example, the output of the Get-Process cmdlet can be piped to the Sort-Object cmdlet (e.g. to sort the objects by handle count) and then to the Where-Object to filter any process that has, say, less than 1 MB of paged memory, then finally to the Select-Object cmdlet to select just the first 10 (i.e. the 10 processes based on handle count).

PowerShell differs from Unix/Linux in that structured .NET objects are passed between stages in the pipeline instead of typically unstructured text. Using objects eliminates the need to explicitly parse text output to extract data. [21]

ScriptingEdit

Windows PowerShell includes a dynamically typed scripting language which can implement complex operations using cmdlets imperatively. The scripting language supports variables, functions, branching (if-then-else), loops (while, do, for, and foreach), structured error/exception handling and closures/lambda expressions[22], as well as integration with .NET. Variables in PowerShell scripts have names that start with $; they can be assigned any value, including the output of cmdlets. Strings can be enclosed either in single quotes or in double quotes: when using double quotes, variables will be expanded even if they are inside the quotation marks. According to the variable syntax, if the path to a file is enclosed in braces preceded by a dollar sign (as in ${C:\foo.txt}), it refers to the contents of the file. If it is used as an L-value, anything assigned to it will be written to the file. When used as an R-value, it will be read from the file. If an object is assigned, it is serialized before storing it.

Object members can be accessed using . notation, as in C# syntax. PowerShell provides special variables, such as $args, which is an array of all the command line arguments passed to a function from the command line, and $_, which refers to the current object in the pipeline.[23] PowerShell also provides arrays and associative arrays. The PowerShell scripting language also evaluates arithmetic expressions entered on the command line immediately, and it parses common abbreviations, such as GB, MB, and KB.

Using the function keyword, PowerShell provides for the creation of functions, which can take parameters. A common problem for people new to PowerShell is that function arguments are separated by spaces, not commas:

  1. <function> <param1> <param2>: Calls the function with two arguments. (These arguments may be bound to parameters declared in the function definition or accessed by position from the $args array.)
  2. <function>(<param1>, <param2>): Calls the function with a single argument, a two element array.

PowerShell allows any .NET methods to be called by providing their namespaces enclosed in brackets ([]), and then using a pair of colons (::) to indicate the static method.[24] For example, [System.Console]::WriteLine("PowerShell"). Objects are created using the New-Object cmdlet. Calling methods of .NET objects is accomplished by using the regular . notation.[24]

For error handling, PowerShell provides a .NET-based exception handling mechanism. In case of errors, objects containing information about the error (Exception object) are thrown, which are caught using the trap keyword. However, the action-or-error is configurable; in case of an error, PowerShell can be configured to silently resume execution, without trapping the exception.[25]

Scripts written using PowerShell can be made to persist across sessions in a .ps1 file. Later, either the entire script or individual functions in the script can be used. Scripts and functions are used analogously with cmdlets, in that they can be used as commands in pipelines, and parameters can be bound to them. Pipeline objects can be passed between functions, scripts, and cmdlets seamlessly. However, script execution is disabled by default and must be enabled explicitly.[26] PowerShell scripts can be signed to verify their integrity, and are subject to Code Access Security.

The PowerShell scripting language supports binary prefix notation similar to the scientific notation supported by many programming languages in the C-family.

HostingEdit

Another use of PowerShell is being embedded in a management application, which then uses the PowerShell runtime to implement the management functionality. For this, PowerShell provides a managed hosting API. Via the APIs, the application can instantiate a runspace (one instantiation of the PowerShell runtime), which runs in the application's process and is exposed as a Runspace object.[1] The state of the runspace is encased in a SessionState object. When the runspace is created, the Windows PowerShell runtime initializes the instantiation, including initializing the providers and enumerating the cmdlets, and updates the SessionState object accordingly. The Runspace then must be opened for either synchronous processing or asynchronous processing. After that it can be used to execute commands.

To execute a command, a pipeline (represented by a Pipeline object) must be created and associated with the runspace. The pipeline object is then populated with the cmdlets that make up the pipeline. For sequential operations (as in a PowerShell script), a Pipeline object is created for each statement and nested inside another Pipeline object.[1] When a pipeline is created, Windows PowerShell invokes the pipeline processor, which resolves the cmdlets into their respective assemblies (the command processor) and adds a reference to them to the pipeline, and associates them with an InputPipe, Outputpipe and ErrorOutputPipe objects, to represent the connection with the pipeline. The types are verified and parameters bound using reflection.[1] Once the pipeline is set up, the host calls the Invoke() method to run the commands, or its asynchronous equivalent - InvokeAsync(). If the pipeline has the Write-Host cmdlet at the end of the pipeline, it writes the result onto the console screen. If not, the results are handed over to the host, which might either apply further processing or display it itself.

The hosting APIs are used by Microsoft Exchange Server 2007 to provide its management GUI. Each operation exposed in the GUI is mapped to a sequence of PowerShell commands (or pipelines). The host creates the pipeline and executes them. In fact, the interactive PowerShell console itself is a PowerShell host, which interprets the scripts entered at command line and creates the necessary Pipeline objects and invokes them.

VersionsEdit

Initially using the code name "Monad", PowerShell was first shown publicly at the Professional Developers Conference in September 2003. There are currently three versions of PowerShell supported by Microsoft.[27]

Version 1.0Edit

Version 1.0 was released in 2006 for Windows XP SP2/SP3, Windows Server 2003, and Windows Vista. For Windows Server 2008, it is included as an optional feature.

Version 2.0Edit

Version 2.0 is integrated with Windows 7 and Windows Server 2008 R2 and is released for Windows XP with Service Pack 3, Windows Server 2003 with Service Pack 2 and Windows Vista with Service Pack 1.[28]

Talaksan:GPowerShell.PNG

Microsoft released PowerShell 2.0 with Windows 7 and Windows 2008 R2. Windows PowerShell 2.0 is installed by default on Windows Server 2008 R2 (except on Core installations where it is optional) and Windows 7. [29] For older platforms it is available via the Windows Management Framework.[30] PowerShell V2 includes changes to the scripting language and hosting API, in addition to including more than 240 new cmdlets.[31][32] It's available here [33]

A non-exhaustive list of the new features included in PowerShell V2 is: [34] [35] [36]

  • PowerShell Remoting: Using WS-Management, PowerShell 2.0 allows scripts and cmdlets to be invoked on a remote machine or a large set of remote machines.
  • Background Jobs: Also called a PSJob, it allows a command sequence (script) or pipeline to be invoked asynchronously. Jobs can be run on the local machine or on multiple remote machines. An interactive cmdlet in a PSJob blocks the execution of the job until user input is provided.
  • Transactions: Enable cmdlet and developers can perform transactional operations. PowerShell 2.0 includes transaction cmdlets for starting, committing, and rolling back a PSTransaction as well as features to manage and direct the transaction to the participating cmdlet and provider operations. The PowerShell Registry provider supports transactions.
  • ScriptCmdlets: These are cmdlets written using the PowerShell scripting language. NOTE: The preferred name for script cmdlets is now Advanced Functions.
  • SteppablePipelines: This allows the user to control when the BeginProcessing(), ProcessRecord() and EndProcessing() functions of a cmdlet are called.
  • Modules: This allows script developers and administrators to organize and partition PowerShell scripts in self-contained, reusable units. Code from a module executes in its own self-contained context and does not affect the state outside of the module. Modules can define a restricted runspace environment by using a script. They have a persistent state as well as public and private members.
  • Data Language: A domain-specific subset of the PowerShell scripting language, that allows data definitions to be decoupled from the scripts and allow localized string resources to be imported into the script at runtime (Script Internationalization).
  • Script Debugging: It allows breakpoints to be set in a PowerShell script or function. Breakpoints can be set on lines, line & columns, commands and read or write access of variables. It includes a set of cmdlets to control the breakpoints via script.
  • Eventing: This feature allows listening, forwarding, and acting on management and system events. Eventing allows PowerShell hosts to be notified about state changes to their managed entities. It also enables PowerShell scripts to subscribe to ObjectEvents, PSEvents, and WmiEvents and process them synchronously and asynchronously.
  • Windows PowerShell Integrated Scripting Environment (ISE): PowerShell 2.0 includes a GUI-based PowerShell host (formerly known as Graphical Windows PowerShell) that provides integrated debugger, syntax highlighting, tab completion and up to 8 PowerShell Unicode-enabled consoles (Runspaces) in a tabbed UI, as well as the ability to run only the selected parts in a script.
  • Network File Transfer: Native support for prioritized, throttled, and asynchronous transfer of files between machines using the Background Intelligent Transfer Service (BITS).[37]
  • New Cmdlets: Including Out-GridView, which displays tabular data in the WPF GridView object.
  • New Operators: -Split, -Join, and Splatting (@) operators.
  • Exception Handling with Try-Catch-Finally: Unlike other .NET languages, this allows multiple exception types for a single catch block.
  • Nestable Here-Strings: PowerShell Here-Strings have been improved and can now nest.[38]
  • Block Comments: PowerShell 2.0 supports block comments using <# and #> as delimiters.[39]
  • New APIs: The new APIs range from handing more control over the PowerShell parser and runtime to the host, to creating and managing collection of Runspaces (RunspacePools) as well as the ability to create Restricted Runspaces which only allow a configured subset of PowerShell to be invoked. The new APIs also support participation in a Windows PowerShell managed transaction.

Version 3.0Edit

A new community technology preview 2 (CTP 2) version of Windows Management Framework 3.0 was released by Microsoft in December, 2011. [40]

Comparison of cmdlets with similar commandsEdit

The following table contains a selection of the cmdlets that ship with PowerShell, noting the most similar commands in other well-known command line interpreters.

PowerShell (Cmdlet) PowerShell (Alias) CMD.EXE / COMMAND.COM Unix shell Description
Get-ChildItem gci, dir, ls dir ls List all files / directories in the (current) directory
Get-Content gc, type, cat type cat Get the content of a file
Get-Command gcm help help List available commands
Get-Help help, man help man Help on commands
Clear-Host cls, clear cls clear Clear the screen[Note 1]
Copy-Item cpi, copy, cp copy cp Copy one or several files / a whole directory tree
Move-Item mi, move, mv move mv Move a file / a directory to a new location
Remove-Item ri, del, erase, rmdir, rd, rm del, erase, rmdir, rd rm, rmdir Delete a file / a directory
Rename-Item rni, ren, mv ren, rename mv Rename a file / a directory
Get-Location gl, pwd cd pwd Display the current directory/present working directory.
Pop-Location popd popd popd Change the current directory to the directory most recently pushed onto the stack
Push-Location pushd pushd pushd Push the current directory onto the stack
Set-Location sl, cd, chdir cd, chdir cd Change the current directory
Tee-Object tee n/a tee Pipe input to a file or variable, then pass the input along the pipeline
Write-Output echo, write echo echo Print strings, variables etc. to standard output
Get-Process gps, ps tlist,[Note 2] tasklist[Note 3] ps List all currently running processes
Stop-Process spps, kill kill,[Note 2] taskkill[Note 3] kill[Note 4] Stop a running process
Select-String n/a find, findstr grep Print lines matching a pattern
Set-Variable sv, set set env, export, set, setenv Set the value of a variable / create a variable

Notes
Suleras:Reflist

ExamplesEdit

Examples are provided first using the long-form canonical syntax and then using more terse UNIX-like and DOS-like aliases that are set up in the default configuration. For a list of all aliases, use the Get-Alias Cmdlet.

  • Stop all processes that begin with the letter p:

PS> Get-Process p* | Stop-Process

PS> ps p* | kill

  • Find the processes that use more than 1000 MB of memory and kill them:

PS> Get-Process | Where-Object { $_.WS -gt 1000MB } | Stop-Process

PS> ps | ? { $_.WS -gt 1000MB } | kill

  • Calculate the number of bytes in the files in a directory:

PS> Get-Childitem | Measure-Object -Property Length -Sum

PS> ls | measure length -s

PS> dir | measure length -s

  • Determine whether a specific process is no longer running:

PS> $processToWatch = Get-Process Notepad PS> $processToWatch.WaitForExit()

PS> (ps notepad).WaitForExit()

  • Change the case of a string from lower to upper:

PS> 'hello, world!'.ToUpper()

  • Insert the string 'ABC' after the first character in the word 'string' to have the result 'sABCtring':

PS> 'string'.Insert(1, 'ABC')

  • Download a specific RSS feed and show the titles of the 8 most recent entries:

PS> $rssUrl = 'http://blogs.msdn.com/powershell/rss.aspx' PS> $blog = [xml](new-object System.Net.WebClient).DownloadString($rssUrl) PS> $blog.rss.channel.item | select title -first 8

PS> $x = new-object xml PS> $x.load('http://blogs.msdn.com/powershell/rss.aspx') PS> $x.rss.channel.item | select title -f 8

  • Sets $UserProfile to the value of the UserProfile environment variable

PS> $UserProfile = $env:UserProfile

  • Call a static method of a .Net object

PS> [System.Math]::Sqrt(16) 4

  • Run a command line executable with arguments:

PS> [Array]$arguments = '-h', '15', 'www.wikipedia.com' PS> tracert $arguments

  • Get the serial number of a remote computer from WMI:

PS> Get-WmiObject -ComputerName MyServer -Class Win32_BIOS | Select-Object SerialNumber

PS> gwmi -co MyServer Win32_BIOS | select SerialNumber

File extensionsEdit

  • PS1 – Windows PowerShell shell script
  • PS1XML – Windows PowerShell format and type definitions
  • PSC1 – Windows PowerShell console file
  • PSD1 – Windows PowerShell data file (for Version 2)
  • PSM1 – Windows PowerShell module file (for Version 2)

Application supportEdit

Snap-ins and hostsEdit

Application Version Cmdlets Provider Management GUI
Exchange Server 2007 Suleras:Yes Suleras:Yes Suleras:Yes
Windows Server 2008 Suleras:Yes Suleras:Yes Suleras:No
Microsoft SQL Server 2008 Suleras:Yes Suleras:Yes Suleras:No
System Center Operations Manager 2007 Suleras:Yes Suleras:Yes Suleras:No
System Center Virtual Machine Manager 2007 Suleras:Yes Suleras:Yes Suleras:Yes
System Center Data Protection Manager 2007 Suleras:Yes Suleras:No Suleras:No
Windows Compute Cluster Server 2007 Suleras:Yes Suleras:Yes Suleras:No
Microsoft Transporter Suite for Lotus Domino[41] 08.02.0012 Suleras:Yes Suleras:No Suleras:No
Microsoft PowerTools for Open XML[42] 1.0 Suleras:Yes Suleras:No Suleras:No
IBM WebSphere MQ[43] 6.0.2.2 Suleras:Yes Suleras:No Suleras:No
Quest Management Shell for Active Directory[44] 1.1 Suleras:Yes Suleras:No Suleras:No
Special Operations Software Specops Command[45] 1.0 Suleras:Yes Suleras:No Suleras:Yes
VMware PowerCLI[46] 5.0.1 Suleras:Yes Suleras:No Suleras:Yes
Internet Information Services[47] 7.0 Suleras:Yes Suleras:Yes Suleras:No
Windows 7 Troubleshooting Center[48] 6.1 Suleras:Yes Suleras:No Suleras:Yes
Microsoft Deployment Toolkit 2010 Suleras:Yes Suleras:No Suleras:No
NetApp Data ONTAP PowerShell Toolkit[49] 1.7 Suleras:Yes Suleras:Yes Suleras:Yes
JAMS Scheduler - Job Access & Management System[50] 5.0 Suleras:Yes Suleras:Yes Suleras:Yes
UIAutomation[51] 0.7 Suleras:Yes Suleras:No Suleras:No
Dell Equallogic[52] 3.5 Suleras:Yes Suleras:No Suleras:No

Alternative implementationEdit

A project named Pash was attempted to create an open source and cross-platform implementation of PowerShell via the Mono framework. Pash was maintained by Igor Moochnick, written in C# and was released under the GNU General Public License. Pash development ceased in 2008 and is currently only partially complete.[53]

See alsoEdit

ReferencesEdit

Suleras:Reflist

Further readingEdit

External linksEdit

Suleras:Windows Components Suleras:Windows commands Suleras:DotNET Suleras:Microsoft APIsar:ويندوز باورشيل ca:Windows PowerShell cs:Windows PowerShell de:Windows PowerShell es:Windows PowerShell fa:ویندوز پاورشل fr:Windows PowerShell ko:윈도 파워셸 id:Windows PowerShell it:Windows PowerShell nl:Windows PowerShell ja:Windows PowerShell pl:Windows PowerShell pt:Windows PowerShell ru:Windows PowerShell fi:Windows PowerShell tr:Windows PowerShell uk:Windows PowerShell yi:Windows PowerShell

zh:Windows PowerShell


The Ponente Justice 06:54, Abril 17, 2012 (UTC)


Kamalian sa pagtukoy: Umiiral na ang mga tatak na <ref>, subalit walang natagpuang tatak na <references/>
Kamalian sa pagtukoy: Umiiral na ang tatak na <ref> para sa pangkat na pinangalanang "Note", subalit walang natagpuang katumbas na tatak na <references group="Note"/>

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Also on FANDOM

Random Wiki