Windows PowerShell Help

  • Windows PowerShell Getting Started Guide

  • Windows PowerShell User's Guide

  • Windows PowerShell About Help Topics

  • Windows PowerShell Cmdlet Help Topics

  • Windows PowerShell Provider Help Topics

  • Windows PowerShell Integrated Scripting Environment (ISE) Help

  • PowerShell.exe Console Help


Windows PowerShell Getting Started Guide

Windows PowerShell is a new Windows command-line shell designed especially for system administrators. The Windows PowerShell 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 Framework common language runtime (CLR) and the .NET Framework, and accepts and returns .NET Framework 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.


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 Framework 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.

This section includes the following topics:

  • Windows PowerShell Cmdlets

  • A New Scripting Language

  • Windows Commands and Utilities

  • Processing Objects

  • Object Pipelines


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 an example that demonstrate use of the cmdlet.


A New Scripting Language

Windows PowerShell uses its own language, rather than reusing existing languages, for the following reasons.

  • Windows PowerShell needed a language for managing Microsoft .NET Framework 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 Framework 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 graphical user interface, such as Notepad and Calculator, at the Windows Powershell prompt. You can also capture the text that Windows programs generate and use that text in Windows PowerShell.

For example, the following commands use Windows, the IPConfig, Net, and Shutdown commands.

C:\PS> net localgroup administrators /add domain01\user01
The command completed successfully.

C:\PS> ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
       Connection-specific DNS Suffix  . : domain.corp.fabricam.com
       IP Address. . . . . . . . . . . . : 142.20.152.115
       Subnet Mask . . . . . . . . . . . : 255.255.252.0
       Default Gateway . . . . . . . . . : 172.30.180.1

C:\PS> shutdown -r

You can even use Windows PowerShell cmdlets, like Select-String, to manipulate the text that Windows programs return.

For example, the following command uses a pipeline operator to send the results of an IPConfig command to the Windows PowerShell Select-String cmdlet, which searches for text in strings. In this case, you use Select-String to find the pattern "255" in the IpConfig output.

C:\PS> ipconfig | select-string -pattern 255
Subnet Mask . . . . . . . . . . . : 255.255.252.0

When a Windows command or tool has parameters, such as the "-r" (restart) parameter of Shutdown, Windows PowerShell passes the parameters to the tool without interpreting them.

However, if the tool uses a Windows PowerShell reserved word, or uses a command format that is unfamiliar to Windows PowerShell, such as Nant's "-D:debug=false" parameter (Windows PowerShell interprets this as two parameters, "-D" and "debug=false"), enclose the parameters in quotations marks to indicate to Windows PowerShell that it should send the parameters to the tool without interpretation.


Processing Objects

Although you might not realize it at first, when you work in Windows PowerShell, you are working with .NET Framework 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 Framework object is an instance of a .NET Framework 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 send 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 commands, that is, to pass the output of one command to another command as input. In a traditional command-line environment, you would have to manipulate text to convert output from one format to another and to remove titles and column headings.

Windows PowerShell provides a new architecture 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 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

This section contains the following topics:

  • An Interactive Environment

  • Support for 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_execution_policies

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.

See Also

  • about_Scripts
  • about_Execution_Policies


Starting Windows PowerShell

You can start Windows PowerShell from the Start menu, from the Taskbar, from the Search or Run box, from a Command Prompt window, or even from another Windows PowerShell window.

And you can start multiple instances of Windows PowerShell (or Windows PowerShell ISE) on a single computer.

How to Start Windows PowerShell

On Windows Vista, Windows Server 2008, and later versions of Windows, to start Windows PowerShell from the Start menu, click Start, click All Programs, click Accessories, click the Windows PowerShell folder, and then click the Windows PowerShell item.

On Windows XP and Windows Server 2003, to start Windows PowerShell from the Start menu, click Start, click Programs, click Accessories, click the Windows PowerShell folder, and then click the Windows PowerShell item.

How to Start Windows PowerShell ISE

Windows PowerShell Integrated Scripting Environment (ISE) is a new host application that lets you run commands, and write, test, and debug scripts in a friendly, syntax-colored, environment.

In Windows Vista, Windows Server 2008, and later versions of Windows, to start Windows PowerShell ISE, from the Start menu, click Start, click All Programs, click Accessories, click the Windows PowerShell folder, and then click the Windows PowerShell ISE item.

In Windows XP and Windows Server 2003, to start Windows PowerShell from the Start menu, click Start, click Programs, click Accessories, click the Windows PowerShell folder, and then click the Windows PowerShell ISE item.

How to Start Windows PowerShell with All Modules

In Windows 7 and Windows Server 2008 R2, you can use a task to start a Windows PowerShell window that includes all the commands that are available to you from optional modules and snap-ins, including those that would not otherwise be added by default. The window also has the privileges of your Administrator account.

For more information about Windows PowerShell modules and snap-ins, see Using Modules and Snap-Ins, How to Import a Module, and about_Modules.

To start Windows PowerShell with all modules, use either of the following procedures.

  • In the taskbar, right-click the Windows PowerShell icon, and then click Import All Modules.

Click Start, click Administrative Tools and then click Windows PowerShell Modules.

Note:

In Windows Server 2008 R2, the Windows PowerShell icon is pinned to the taskbar by default. However, you must start Windows PowerShell one time to make the Import All Modules task appear.

In all supported versions of Windows, you can add all available modules to a Windows PowerShell session. Start Windows PowerShell and, at the Windows PowerShell prompt, type:

get-module -listAvailable | import-module

How to Start Windows PowerShell with Administrator Privileges

In Windows 7 and Windows Server 2008 R2, you can use a task to start a Windows PowerShell window with all the privileges of the your Administrator account. Typically, this is not necessary, but there are a few commands that require these privileges.

In the Windows taskbar, right-click the Windows PowerShell icon, and then click Run Windows PowerShell as admin.

To start Windows PowerShell (or Windows PowerShell ISE) with Administrator privileges in all supported versions of Windows, use the following procedure.

  1. Click Start, click Programs, click Accessories, and click the Windows PowerShell folder.

  2. Right-click the Windows PowerShell item (or the Windows PowerShell ISE item), and then click Run as administrator.

How to Start Windows PowerShell with Other Options

Windows PowerShell has numerous options that let you start a customized Windows PowerShell session, including options that use a particular console file, run with a particular execution policy, exclude your Windows PowerShell profile, run a particular command or script, or use a single-threaded apartment, among many others.

To view these options, in a Command Prompt (Cmd.exe) window, or in an existing Windows PowerShell window, type:

powershell -?

To start Windows PowerShell with a particular option, use the parameter for the option. For example, to start Windows PowerShell with the RemoteSigned execution policy, type:

powershell -executionPolicy RemoteSigned


Using Windows PowerShell

This section explains the basics of using Windows PowerShell. First, it describes the Get-Help cmdlet (pronounced "command-let"), 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 how to format the output of the cmdlets to get the data required to create a useful display. Finally, it shows how to use aliases in Windows PowerShell, how to run traditional Windows applications in Windows PowerShell, and how to manage errors.

This section includes the following topics:

  • Getting Help: Get-Help

  • Using Cmdlets

  • Learning About Objects: Get-Member

  • Formatting Command Output

  • Using Aliases

  • Using Windows Programs

  • Managing Errors


Getting Help: Get-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 learn how to use Windows PowerShell.

The first topic of interest might be the Help system itself. 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 Help for a cmdlet, type "get-help" followed 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 more information about execution policies, type:

get-help about_execution_policies

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 parameter. 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 *

Windows PowerShell Help is also available online in the Microsoft TechNet library under the Windows PowerShell topic. The online version of the Help is often more easy to read and it is more frequently updated than the Help that is displayed at the command prompt.

In Windows PowerShell v.2, you can use the Online parameter of the Get-Help cmdlet to display the online version of a cmdlet Help topic. By default, the Online parameter links to the TechNet Library Help topics.

For example, to open the online version of the Help topic for the Get-Process cmdlet, type:

get-help get-process -online

You can also use one of the Windows PowerShell functions that call Get-Help. The Help function displays one screen 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-*

The Help topics that explain concepts in Windows PowerShell begin with "about_". To display Help about a Windows PowerShell concept, type "get-help" followed by the concept name. (The concept name must be entered in English, even in non-English versions of Windows PowerShell.)

For example, to get Help about wildcards, type:

get-help about_wildcards

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 will learn how to use Windows PowerShell.

See Also

  • Get-Help
  • Get-Command


Using Cmdlets

A cmdlet 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 commands 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 of Get-Command.

PS> get-command -name *.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 Get-WmiObject. This cmdlet enables you to 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


Using Functions

In addition to running cmdlets, you can also run functions in Windows PowerShell. Windows PowerShell comes with built-in functions, and you can add functions that you get from other users and write your own functions.

About Functions

Functions are a type of command in Windows PowerShell. You run a function by typing its name, just like you run a cmdlet. Functions can have parameters just like cmdlets. Functions can take .NET objects as input and return .NET objects as output just like cmdlets. In fact, functions can do just about everything that cmdlets can do.

The best thing about functions is that they are really easy to write. Unlike cmdlets, which are written in C#, functions are just a named grouping of Windows PowerShell commands and expressions. If you can type commands in Windows PowerShell, you can write functions.

Finding Functions

Functions are commands, so to find functions, use the Get-Command cmdlet.

For example, to find all functions in your session, type:

get-command -CommandType function

Windows PowerShell also comes with a Function: drive that contains all functions in your session. To navigate in the Function: drive, use the same methods that you use to navigate in the file system drives.

To enter the function drive, type:

cd function:

To display the functions in the function drive, type:

dir function:

Running Functions

To run a function, just type the function name. For example, to run the Clear-Host function, type:

clear-host

In the Windows PowerShell Console, the Clear-Host function deletes all of the text in the console window. It might behave differently or have no effect in other hosting programs.

To use the parameters of a function, type the parameter name preceded, by a hyphen and followed by a value, just as would do for the parameters of a cmdlet.

For example, the Help function, which displays Help topics one page at a time, has the same parameters as the Get-Help cmdlet. To use the Help function to get only the examples in the Help topic for the Get-Service cmdlet, type:

help -name get-service -examples

Getting Help for Functions

Functions can have Help topics. To find the Help topic for a function, use the Get-Help cmdlet. This is the same cmdlet that you use to get Help for cmdlets.

For example, to get Help for the Disable-PSRemoting function, type:

get-help Disable-PSRemoting

You can use all of the parameters of the Get-Help cmdlet to get Help for functions. For example, to get only the examples in the Help topic for the Disable-PSRemoting function, type:

get-help Disable-PSRemoting -example

Writing Functions

A function is a named group of commands or expressions. To write a simple function, use the following format.

function <name> { <commands> }

Just type function, a name for the function, and enclose the commands in braces ({ }).

For example, if you repeatedly type a particular command, such as get-help get-member -examples, you can save time by writing a function that runs the command. The following function, called GMEX, runs the command.

function GMEX {get-help get-member -examples}

After you type the function at the Windows PowerShell prompt (or copy and paste it from this topic) and then press ENTER, you can use the function in your session. To run the function, type GMEX.

This is a simple function, but with just a few more lines, you can add parameters, make the parameters optional or mandatory, add user messages, and add a Help topic for your function. When you learn more about Windows PowerShell, you can write advanced functions that have all of the features of cmdlets.

For more information about writing functions, see about_Functions, about_Comment_Based_Help, and about_Functions_Advanced.

Saving Functions

When you open Windows PowerShell, you are in a Windows PowerShell session. The session lasts until you close the Windows PowerShell window (or type Exit to end the session). Unless you save an item to a file on disk or save it in the registry, the items that you create in your session are deleted when your session ends.

To save the functions that you write so that they are available in future Windows PowerShell sessions, create a Windows PowerShell profile and save your functions in your profile.

For more information, see about_Profiles.

See Also

    Using Cmdlet Parameters
  • about_Functions
  • about_Functions_Advanced
  • about_Command_Syntax
  • about_Comment_Based_Help
  • about_Profiles
  • Using Cmdlets


Using Modules and Snap-Ins

Windows PowerShell is a fully extensible environment. Anyone can write commands for Windows PowerShell. You can use commands that others write and share the commands that you write with others.

Commands are shared by using modules and snap-ins. Windows PowerShell modules and snap-ins are packages that contain Windows PowerShell commands and other items. All cmdlets and providers in Windows PowerShell are delivered in snap-ins or modules, and modules can also contain functions, aliases, variables, and drives.

Some snap-ins and modules are added automatically to every Windows PowerShell session. If you receive a snap-in or module, you can install it and add the commands to your Windows PowerShell sessions. To share the commands that you write, you can create a Windows PowerShell module or snap-in.

About Modules

A module is a package of commands and other items that you can use in Windows PowerShell. After you run the setup program or save the module to disk, you can import the module into your Windows PowerShell session and use the commands and items. You can also use modules to organize the cmdlets, providers, functions, aliases, and other commands that you create, and share them with others.

For information about installing and using modules, see about_Modules. For information about creating modules, see "Writing a Windows PowerShell Module" in MSDN.

About Snap-ins

A Windows PowerShell snap-in (PSSnapin) is a dynamic link library (.dll) that implements cmdlets and providers. When you receive a snap-in, you need to install it, and then you can add the cmdlets and providers in the snap-in to your Windows PowerShell session.

For information about installing and using snap-ins, see about_PSSnapins. For information about writing snap-ins, see "How to Write a Windows PowerShell Snap-in" in MSDN.


How to Import a Module

Modules are packages of Windows PowerShell commands, such as cmdlets and functions, and items, such as providers, variables, aliases and drives. If you have downloaded, installed, or received a module, use the procedure that is described in this topic to import or add it to your Windows PowerShell session.

Before Importing: Install the Module

If you receive a module as a folder with files in it, you need to install it on your computer before you can import it into Windows PowerShell. Typically, installing is just copying the module to a particular location on a drive that your computer can access.

Most modules are installed for you. Windows PowerShell comes with several pre-installed modules. In Windows Server 2008 R2, the Add Features Wizard in Server Manager automatically installs the feature modules that you select. Many other modules come in an installer or setup program that installs the module.

For information about installing modules, see about_Modules.

How to Import a Module

To use the commands in a module, import the module into a Windows PowerShell session. To import modules from a default module location into the current session, use the following command format.

import-module <module-name>

For example, the following command imports the BitsTransfer module into the current session.

import-module BitsTransfer

To import a module that is not in a default module location, use the fully qualified path to the module folder in the command. For example, to add the TestCmdlets module in the C:\ps-test directory to your session, type:

import-module c:\ps-test\TestCmdlets

For more information about adding modules to your session, see Import-Module.

See Also

  • about_Modules
  • Import-Module


Learning About Objects: Get-Member

One of the most useful cmdlets is Get-Member, which displays information about the .NET Framework 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 more information about the Get-Member command, type:

get-help get-member -detailed


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 always there 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 order 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 Framework 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 output, 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 environment 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 Windows PowerShell, 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 data that is not valid or if you do not have the permissions required to perform the command, Windows PowerShell generates a 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

This section contains the following topics:

  • Navigating the File System

  • Navigating the Registry

  • Navigating the Certificate Store

  • Navigating Other Drives

  • About Windows PowerShell Drives

  • Drives and Providers


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 hive 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, Windows PowerShell displays 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. The certificate store maps to the Windows 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 Framework 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_providers

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.

This section contains the following topics:

  • Examining the Execution Policy

  • Windows PowerShell Profiles


Examining the Execution Policy

Scripting is a very powerful tool, but it can be misused 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_execution_policies

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.

See Also

  • about_Execution_Policies
  • about_Signing
  • Get-ExecutionPolicy
  • Set-ExecutionPolicy


Windows PowerShell Profiles

When you add aliases, functions, and variables, 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 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

When you create or import variables, aliases, or functions, or add a Windows PowerShell snap-in, these elements are added only to the current session. If you exit the session or close the window, they are gone.

To save the variables, aliases, functions, and commands that you use routinely, and make them available in every Windows PowerShell session, add them to your Windows PowerShell profile.

You can also create, share, and distribute profiles to enforce a consistent view of Windows PowerShell in a larger enterprise.

Windows PowerShell 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 Windows PowerShell user profile. The location of this profile is stored in the $profile variable.

To display the path to the Windows PowerShell profile, type:

$profile

To determine whether a Windows PowerShell profile has been created on the system, type:

test-path $profile

If the profile exists, the response is True; otherwise, it is False.

To create a Windows PowerShell profile file, 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 $env:windir\System32\WindowsPowerShell\v1.0\profile.ps1 -itemtype file -force

The profile is effective only when the file is located exactly in the path and with the file name that is stored in the $profile variable. Therefore, if you create a profile in Notepad and then save it, or if you copy a profile to your system, be sure to save the file in the path and with the file name specified in the $profile variable.

If you create a profile in Notepad, enclose the file name in quotation marks to preserve the PS1 file name extension. For example:

"Microsoft.PowerShell_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 use routinely. One very helpful opens your user 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.


Introducing Windows PowerShell ISE

To start Windows PowerShell ISE

  1. In Windows Vista, Windows Server 2008, and later versions of Windows, from the Start menu, click Start, click All Programs, click Accessories, click the Windows PowerShell folder, and then click the Windows PowerShell ISE item.

  2. In Windows XP and Windows Server 2003, to start Windows PowerShell, from the Start menu, click Start, click Programs, click Accessories, click the Windows PowerShell folder, and then click the Windows PowerShell ISE item.

  3. In the Windows PowerShell console, Cmd.exe, or in the Run box, type "powershell_ise.exe”.

To get Help in Windows PowerShell ISE

  • From the Help menu of the Windows PowerShell ISE, click Windows PowerShell Help, or press F1.

    The file that opens describes Windows PowerShell ISE and Windows PowerShell, including all the Help available from the Get-Help cmdlet.


Windows PowerShell User's Guide

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

Audience

The Windows PowerShell User's Guide is intended for IT professionals, programmers, and power users who have no prior background with Windows PowerShell. Although backgrounds in scripting and Windows Management Instrumentation (WMI) are helpful, they are not assumed or required to understand this document.


Windows PowerShell Basics

Graphical user interfaces use some basic concepts that are well known to most computer users. Users rely on the familiarity of those interfaces to accomplish tasks. Operating systems present users with a graphical representation of items that can be browsed, usually with drop-down menus for accessing specific functionality and context menus for accessing context-specific functionality.

A command-line interface (CLI), such as Windows PowerShell, must use a different approach to expose information, because it does not have menus or graphical systems to help the user. You need to know command names before you can use them. Although you can type complex commands that are equivalent to the features in a GUI environment, you must become familiar with commonly-used commands and command parameters.

Most CLIs do not have patterns that can help the user to learn the interface. Because CLIs were the first operating system shells, many command names and parameter names were selected arbitrarily. Terse command names were generally chosen over clear ones. Although help systems and command design standards are integrated into most CLIs, they have been generally designed for compatibility with the earliest commands, so the command set is still shaped by decisions made decades ago.

Windows PowerShell was designed to take advantage of a user's historic knowledge of CLIs. In this chapter, we will talk about some basic tools and concepts that you can use to learn Windows PowerShell quickly. They include:

  • Using Get-Command

  • Using Cmd.exe and UNIX commands

  • Using External Commands

  • Using Tab-Completion

  • Using Get-Help


About Windows PowerShell

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

Discoverability

Windows PowerShell makes it easy to discover its features. For example, to find a list of cmdlets that view and change Windows services, type:

get-command *-service

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

get-help get-service

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

get-service | get-member

Consistency

Managing systems can be a complex endeavor and tools that have a consistent interface help to control the inherent complexity. Unfortunately, neither command-line tools nor scriptable COM objects have been known for their consistency.

The consistency of Windows PowerShell is one of its primary assets. For example, if you learn how to use the Sort-Object cmdlet, you can use that knowledge to sort the output of any cmdlet. You do not have to learn the different sorting routines of each cmdlet.

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

Interactive and Scripting Environments

Windows PowerShell is a combined interactive and scripting environment that gives you access to command-line tools and COM objects, and also enables you to use the power of the .NET Framework Class Library (FCL).

This environment improves upon the Windows Command Prompt, which provides an interactive environment with multiple command-line tools. It also improves upon Windows Script Host (WSH) scripts, which let you use multiple command-line tools and COM automation objects, but do not provide an interactive environment.

By combining access to all of these features, Windows PowerShell extends the ability of the interactive user and the script writer, and makes system administration more manageable.

Object Orientation

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

Easy Transition to Scripting

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


Installing and Running Windows PowerShell

Installation Requirements

Before you install Windows PowerShell, be sure that your system has the software programs that Windows PowerShell requires. Windows PowerShell requires the following programs:

  • Windows XP Service Pack 2, Windows 2003 Service Pack 1, or later versions of Windows

  • Microsoft .NET Framework 2.0

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

Installing Windows PowerShell

To install Windows PowerShell:

  1. Download the Windows PowerShell installation file. (The name of the file will differ with the platform, operating system, and language pack.)

  2. To start the installation, click Open.

  3. Follow the instructions on the installation wizard pages.

You can also save the Windows PowerShell files to a network share for installation on multiple computers.

To perform a silent installation, type:

<PowerShell-exe-file-name> /quiet

For example,

PowerShellSetup_x86_fre.exe /quiet

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

Running Windows PowerShell

To start Windows PowerShell from the Start Menu, click Start, click All Programs, click Windows PowerShell 1.0, and then click the Windows PowerShell icon.

To start Windows PowerShell from the Run box, click Start, click Run, type powershell, and click OK.

To start Windows PowerShell from a Command Prompt (cmd.exe) window, at the command prompt, type powershell. Because Windows PowerShell runs in a console session, you can use this same technique to run it within a remote telnet or SSH session. To return to your Command Prompt session, type exit.


Understanding Important Windows PowerShell Concepts

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

Commands Are Not Text-Based

Unlike traditional command-line interface commands, Windows PowerShell cmdlets are designed to deal with objects - structured information that is more than just a string of characters appearing on the screen. Command output always carries along extra information that you can use if you need it. We will discuss this topic in depth in this document.

If you have used text-processing tools to process command-line data in the past, you will find that they behave differently if you try to use them in Windows PowerShell. In most cases, you do not need text-processing tools to extract specific information. You can access portions of the data directly by using standard Windows PowerShell object manipulation commands.

The Command Family Is Extensible

Interfaces such as Cmd.exe do not provide a way for you to directly extend the built-in command set. You can create external command-line tools that run in Cmd.exe, but these external tools do not have services, such as Help integration, and Cmd.exe does not automatically know that they are valid commands.

The native binary commands in Windows PowerShell, known as cmdlets (pronounced command-lets), can be augmented by cmdlets that you create and that you add to Windows PowerShell by using snap-ins. Windows PowerShell snap-ins are compiled, just like binary tools in any other interface. You can use them to add Windows PowerShell providers to the shell, as well as new cmdlets.

Because of the special nature of the Windows PowerShell internal commands, we will refer to them as cmdlets.

Note:

Windows PowerShell can run commands other than cmdlets. We will not be discussing them in detail in the Windows PowerShell User's Guide, but they are useful to know about as categories of command types. Windows PowerShell supports scripts that are analogous to UNIX shell scripts and Cmd.exe batch files, but have a .ps1 file name extension. Windows PowerShell also allows you to create internal functions that can be used directly in the interface or in scripts.

Windows PowerShell Handles Console Input and Display

When you type a command, Windows PowerShell always processes the command-line input directly. Windows PowerShell also formats the output that you see on the screen. This is significant because it reduces the work required of each cmdlet and ensures that you can always do things the same way regardless of which cmdlet you are using. One example of how this simplifies life for both tool developers and users is command-line Help.

Traditional command-line tools have their own schemes for requesting and displaying Help. Some command-line tools use /? to trigger the Help display; others use -?, /H, or even //. Some will display Help in a GUI window, rather than in the console display. Some complex tools, such as application updaters, unpack internal files before displaying their Help. If you use the wrong parameter, the tool might ignore what you typed and begin performing a task automatically.

When you enter a command in Windows PowerShell, everything you enter is automatically parsed and pre-processed by Windows PowerShell. If you use the -? parameter with a Windows PowerShell cmdlet, it always means "show me Help for this command". Cmdlet developers do not have to parse the command; they only need to provide the Help text.

It is important to understand that the Help features of Windows PowerShell are available even when you run traditional command-line tools in Windows PowerShell. Windows PowerShell processes the parameters and passes the results to the external tools.

Note:

If you run an graphic application in Windows PowerShell, the window for the application opens. Windows PowerShell intervenes only when processing the command-line input you supply or the application output returned to the console window; it does not affect how the application works internally.

Windows PowerShell Uses Some C# Syntax

Windows PowerShell has syntax features and keywords that are very similar to those used in the C# programming language, because Windows PowerShell is based on the .NET Framework. Learning Windows PowerShell will make it much easier to learn C#, if you are interested in the language.

If you are not a C# programmer, this similarity is not important. However, if you are already familiar with C#, the similarities can make learning Windows PowerShell much easier.


Learning Windows PowerShell Names

Learning names of commands and command parameters is a significant time investment with most command-line interfaces. The issue is that there are very few patterns, so the only way to learn is by memorizing each command and each parameter that you need to use on a regular basis.

When you work with a new command or parameter, you cannot generally use what you already know; you have to find and learn a new name. If you look at how interfaces grow from a small set of tools with incremental additions to functionality, it is easy to see why the structure is nonstandard. With command names in particular, this may sound logical since each command is a separate tool, but there is a better way to handle command names.

Most commands are built to manage elements of the operating system or applications, such as services or processes. The commands have a variety of names that may or may not fit into a family. For example, on Windows systems, you can use the net start and net stop commands to start and stop a service. There is another more generalized service control tool for Windows that has a completely different name, sc, that does not fit into the naming pattern for the net service commands. For process management, Windows has the tasklist command to list processes and the taskkill command to kill processes.

Commands that take parameters have irregular parameter specifications. You cannot use the net start command to start a service on a remote computer. The sc command will start a service on a remote computer, but to specify the remote computer, you must prefix its name with a double backslash. For example, to start the spooler service on a remote computer named DC01, you would type sc \\DC01 start spooler. To list tasks running on DC01, you need to use the /S (for "system") parameter and supply the name DC01 without backslashes, like this: tasklist /S DC01.

Although there are important technical distinctions between a service and a process, they are both examples of manageable elements on a computer that have a well-defined life cycle. You may want to start or stop a service or process, or get a list of all currently running services or processes. In other words, although a service and a process are different things, the actions we perform on a service or a process are often conceptually the same. Furthermore, choices we may make to customize an action by specifying parameters may be conceptually similar as well.

Windows PowerShell exploits these similarities to reduce the number of distinct names you need to know to understand and use cmdlets.

Cmdlets Use Verb-Noun Names to Reduce Command Memorization

Windows PowerShell uses a "verb-noun" naming system, where each cmdlet name consists of a standard verb hyphenated with a specific noun. Windows PowerShell verbs are not always English verbs, but they express specific actions in Windows PowerShell. Nouns are very much like nouns in any language, they describe specific types of objects that are important in system administration. It is easy to demonstrate how these two-part names reduce learning effort by looking at a few examples of verbs and nouns.

Nouns are less restricted, but they should always describe what a command acts upon. Windows PowerShell has commands such as Get-Process, Stop-Process, Get-Service, and Stop-Service.

In the case of two nouns and two verbs, consistency does not simplify learning that much. However, if you look at a standard set of 10 verbs and 10 nouns, you then have only 20 words to understand, but those words can be used to form 100 distinct command names.

Frequently, you can recognize what a command does by reading its name, and it is usually apparent what name should be used for a new command. For example, a computer shutdown command might be Stop-Computer. A command that lists all computers on a network might be Get-Computer. The command that gets the system date is Get-Date.

You can list all commands that include a particular verb with the -Verb parameter for Get-Command (We will discuss Get-Command in detail in the next section). For example, to see all cmdlets that use the verb Get, type:

PS> Get-Command -Verb Get
CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Get-Acl                         Get-Acl [[-Path] <String[]>]...
Cmdlet          Get-Alias                       Get-Alias [[-Name] <String[]...
Cmdlet          Get-AuthenticodeSignature       Get-AuthenticodeSignature [-...
Cmdlet          Get-ChildItem                   Get-ChildItem [[-Path] <Stri...
...

The -Noun parameter is even more useful because it allows you to see a family of commands that affect the same type of object. For example, if you want to see which commands are available for managing services, type following command:

PS> Get-Command -Noun Service
CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Get-Service                     Get-Service [[-Name] <String...
Cmdlet          New-Service                     New-Service [-Name] <String>...
Cmdlet          Restart-Service                 Restart-Service [-Name] <Str...
Cmdlet          Resume-Service                  Resume-Service [-Name] <Stri...
Cmdlet          Set-Service                     Set-Service [-Name] <String>...
Cmdlet          Start-Service                   Start-Service [-Name] <Strin...
Cmdlet          Stop-Service                    Stop-Service [-Name] <String...
Cmdlet          Suspend-Service                 Suspend-Service [-Name] <Str...
...

A command is not necessarily a cmdlet, just because it has a verb-noun naming scheme. One example of a native Windows PowerShell command that is not a cmdlet but has a verb-noun name, is the command for clearing a console window, Clear-Host. The Clear-Host command is actually an internal function, as you can see if you run Get-Command against it:

PS> Get-Command -Name Clear-Host

CommandType     Name                            Definition
-----------     ----                            ----------
Function        Clear-Host                      $spaceType = [System.Managem...

Cmdlets Use Standard Parameters

As noted earlier, commands used in traditional command-line interfaces do not generally have consistent parameter names. Sometimes parameters do not have names at all. When they do, they are often single-character or abbreviated words that can be typed rapidly but are not easily understood by new users.

Unlike most other traditional command-line interfaces, Windows PowerShell processes parameters directly, and it uses this direct access to the parameters along with developer guidance to standardize parameter names. Although this does not guarantee that every cmdlet will always conform to the standards, it does encourage it.

Note:

Parameter names always have a '-' prepended to them when you use them, to allow Windows PowerShell to clearly identify them as parameters. In the Get-Command -Name Clear-Host example, the parameter's name is Name, but it is entered as -Name.

Here are some of the general characteristics of the standard parameter names and usages.

The Help Parameter (?)

When you specify the -? parameter to any cmdlet, the cmdlet is not executed. Instead, Windows PowerShell displays help for the cmdlet.

Common Parameters

Windows PowerShell has several parameters known as common parameters. Because these parameters are controlled by the Windows PowerShell engine, whenever they are implemented by a cmdlet, they will always behave the same way. The common parameters are WhatIf, Confirm, Verbose, Debug, Warn, ErrorAction, ErrorVariable, OutVariable, and OutBuffer.

Suggested Parameters

The Windows PowerShell core cmdlets use standard names for similar parameters. Although the use of parameter names is not enforced, there is explicit guidance for usage to encourage standardization.

For example, the guidance recommends naming a parameter that refers to a computer by name as ComputerName, rather than Server, Host, System, Node, or other common alternative words. Among the important suggested parameter names are Force, Exclude, Include, PassThru, Path, and CaseSensitive.


Getting Summary Command Information

The Windows PowerShell Get-Command cmdlet retrieves the names of all available commands. When you type Get-Command at a Windows PowerShell prompt, you will see output similar to the following:

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...
...

This output looks a lot like the Help output of Cmd.exe: a tabular summary of internal commands. In the extract of the Get-Command command output shown above, every command shown has a CommandType of Cmdlet. A Cmdlet is Windows PowerShell's intrinsic command type that corresponds roughly to the dir and cd commands of Cmd.exe and to built-ins in UNIX shells such as BASH.

In the output of the Get-Command command, all the definitions end with ellipses (...) to indicate that PowerShell cannot display all the content in the available space. When Windows PowerShell displays output, it formats the output as text and then arranges it to make the data fit cleanly into the window. We will talk about this later in the section on formatters.

The Get-Command cmdlet has a Syntax parameter that allows you to retrieve just the syntax of each cmdlet. Enter the Get-Command -Syntax command to display the full output:

PS> Get-Command -Syntax
Add-Content [-Path] <String[]> [-Value] <Object[]> [-PassThru] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Force] [Credential <PSCredential>] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-ErrorVariable <String>] [-OutVariable <String>] [-OutBuffer <Int32>] [-WhatIf] [-Confirm] [-Encoding <FileSystemCmdletProviderEncoding>]

Add-History [[-InputObject] <PSObject[]>] [-Passthru] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-ErrorVariable <String>] [-OutVariable <String>][-OutBuffer <Int32>]...

Displaying Available Command Types

The Get-Command command does not list every command that is available in Windows PowerShell. Instead, the Get-Command command lists only the cmdlets in the current shell. Windows PowerShell actually supports several other types of commands. Aliases, functions, and scripts are also Windows PowerShell commands, although they are not discussed in detail in the Windows PowerShell User's Guide. External files that are executables, or have a registered file type handler, are also classified as commands.

You can return a listing of all items that can be invoked by entering the following command:

PS> Get-Command *

Because this list includes external files in your search path, it may contain thousands of items. It is more useful to look at a reduced set of commands. To find native commands of other types, you can use the CommandType parameter of the Get-Command cmdlet. Although we have not talked about these other command types yet, you can still display them if you know the name of the CommandType for a class of commands.

Note:

Although we have not discussed it yet, the asterisk (*) is used for wildcard matching in Windows PowerShell command arguments. The * means "match one or more of any characters". You can type Get-Command a* to find all commands that begin with the letter "a". Unlike wildcard matching in Cmd.exe, Windows PowerShell's wildcard will also match a period.

To display the special command category aliases (these are nicknames used as alternatives to standard command names), enter the following command:

PS> Get-Command -CommandType Alias

To display all Windows PowerShell functions, enter the following command:

PS> Get-Command -CommandType Function

To display external scripts in Windows PowerShell's search path, enter the following command:

PS> Get-Command -CommandType ExternalScript


Getting Detailed Help Information

Windows PowerShell includes detailed Help topics that explain Windows PowerShell concepts and the Windows PowerShell language. There are also Help topics for each cmdlet and provider and Help topics for many functions and scripts.

You can display these Help topics at the command prompt or view the most recently updated versions of these topics in the Microsoft TechNet Library. Many programs that host Windows PowerShell, such as Windows PowerShell Integrated Scripting Environment, provide additional Help features, such as context-sensitive Help and compiled Help file (.chm).

Getting Help for Cmdlets

To get Help about Windows PowerShell cmdlets, use the Get-Help cmdlet. For example, to get Help for the Get-ChildItem cmdlet, type:

get-help get-childitem

or

get-childitem -?

You can even get Help about the Get-Help cmdlet. For example:

get-help get-help

To get a list of all the cmdlet Help topics in your session, type:

get-help -category cmdlet

To display one page of each Help topic at a time, use the help function or its alias man. For example, to display Help for the Get-ChildItem cmdlet, type

man get-childitem

or

help get-childitem

To display detailed information about a cmdlet, function, or script, including descriptions of its parameters and examples of its use, use the Detailed parameter of the Get-Help cmdlet. For example, to get detailed information about the Get-ChildItem cmdlet, type:

get-help get-childitem -detailed

To display all content in the Help topic, use the Full parameter of the Get-Help cmdlet. For example, to display all content in the Help topic for the Get-ChildItem cmdlet, type:

get-help get-childitem -full

To get detailed Help about the parameters of a cmdlet, use the Parameter parameter of the Get-Help cmdlet. For example, to get detailed Help for all of the parameters of the Get-ChildItem cmdlet, type:

get-help get-childitem -parameter *

To display only the examples in a Help topic, use the Example parameter of the Get-Help. For example, to display only the examples in the Help topic for the Get-ChildItem cmdlet, type:

get-help get-childitem -examples

For information about how to write Help topics for the cmdlets that you write, see the "How to Write Cmdlet Help" topic in MSDN.

Getting Conceptual Help

The Get-Help cmdlet also displays information about conceptual topics in Windows PowerShell, including topics about the Windows PowerShell language. Conceptual Help topics begin with the "about_" prefix, such as about_line_editing. (The name of the conceptual topic must be entered in English even on non-English versions of Windows PowerShell.)

To display a list of conceptual topics, type:

get-help about_*

To display a particular Help topic, type the topic name, for example:

get-help about_command_syntax

The parameters of Get-Help, such as Detailed, Parameter, and Examples, have no effect on the display of conceptual Help topics.

Getting Help About Providers

The Get-Help cmdlet displays information about Windows PowerShell providers. To get Help for a provider, type "Get-Help" followed by the provider name. For example, to get Help for the Registry provider, type:

get-help registry

To get a list of all the provider Help topics in your session, type

get-help -category provider

The parameters of Get-Help, such as Detailed, Parameter, and Examples, have no effect on the display of provider Help topics.

Getting Help About Scripts and Functions

Many scripts and functions in Windows PowerShell have Help topics. Use the Get-Help cmdlet to display the Help topics for scripts and functions.

To display the Help for a function, type "get-help" followed by the function name. For example, to get Help for the Disable-PSRemoting function, type:

get-help disable-psremoting

To display the Help for a script, type the fully qualified path to the script file. If the script is in a path that is listed in the Path environment variable, you can omit the path from the command.

For example, if you have a script called "TestScript.ps1" in your C:\PS-Test directory, to display the Help topic for the script, type:

get-help c:\ps-test\TestScript.ps1

The parameters that were designed for displaying cmdlet Help, such as Detailed, Full, Examples, and Parameter, work for script Help and function Help, too. However, when you display all Help, by typing "get-help *", Help for functions and scripts does not appear.

For information about writing Help topics for your functions and scripts, see about_Functions, about_Scripts, and about_Comment_Based_Help.

Getting Help Online

If you are connected to the Internet, one of the best ways to get Help is to view the Help topics online. Because online topics are easy to update, they are likely to provide the most current content.

To get Help online, try the Online parameter of the Get-Help cmdlet. The Online parameter of the Get-Help cmdlet works only for cmdlet Help, function Help, and script Help. You cannot use the Online parameter with conceptual (About) topics or provider Help topics. Also, because this feature is optional, it does not work for every cmdlet, function, or script Help topic.

However, all the Help topics that come with Windows PowerShell, including provider Help and conceptual (About) Help topics, are available online in the Windows PowerShell section of the Microsoft TechNet Library.

To use the Online parameter of the Get-Help cmdlet, use the following command format.

get-help <command-name> -online

For example, to get the online version of the Help topic about the Get-ChildItem cmdlet, type:

get-help get-childitem -online

If an online version of the Help topic is available, it will open in your default browser.

If online Help is supported for a Help topic, you can also view the Internet address (URL) of the Help topic. The Internet address appears in the Related Links section of a Help topic.

For example, to see the URL for the online version of the Add-Computer cmdlet, type:

get-help add-computer

The first line in the Related Links section of the topic is shown below.

Online version: http://go.microsoft.com/fwlink/?LinkID=135194

For information about how to provide online support for your Help topics, see about_Comment_Based_Help, and see "How to Write Cmdlet Help" (http://go.microsoft.com/fwlink/?LinkID=123415) in the MSDN (Microsoft Developer Network) library.

See Also

  • about_Functions
  • about_Scripts
  • about_Comment_Based_Help
  • Get-Help


Using Familiar Command Names

Using a mechanism called aliasing, Windows PowerShell allows users to refer to commands by alternate names. Aliasing allows users with experience in other shells to reuse common command names that they already know to perform similar operations in Windows PowerShell. Although we will not discuss Windows PowerShell aliases in detail, you can still use them as you get started with Windows PowerShell.

Aliasing associates a command name that you type with another command. For example, Windows PowerShell has an internal function named Clear-Host that clears the output window. If you type either the cls or clear command at a command prompt, Windows PowerShell interprets that this is an alias for the Clear-Host function and runs the Clear-Host function.

This feature helps users to learn Windows PowerShell. First, most Cmd.exe and UNIX users have a large repertoire of commands that users already know by name, and although the Windows PowerShell equivalents may not produce identical results, they are close enough in form that users can use them to do work without having to first memorize the Windows PowerShell names. Second, the major source of frustration in learning a new shell when the user is already familiar with another shell, is the errors that are caused by "finger memory". If you have used Cmd.exe for years, when you have a screen full of output and want to clean it up, you would reflexively type the cls command and press the ENTER key. Without the alias to the Clear-Host function in Windows PowerShell, you would simply get the error message "'cls' is not recognized as a cmdlet, function, operable program, or script file." and be left with no idea of what to do to clear the output.

The following is a brief listing of the common Cmd.exe and UNIX commands that you can use inside Windows PowerShell:

cat | dir | mount | rm
cd | echo | move | rmdir
chdir | erase | popd | sleep
clear | h | ps | sort
cls | history | pushd | tee
copy | kill | pwd | type
del | lp | r | write
diff | ls | ren |

If you find yourself using one of these commands reflexively and want to learn the real name of the native Windows PowerShell command, you can use the Get-Alias command:

PS> Get-Alias cls

CommandType     Name                            Definition
-----------     ----                            ----------
Alias           cls                             Clear-Host

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

Interpreting Standard Aliases

Unlike the aliases described above, which were designed for name-compatibility with other interfaces, the aliases built into Windows PowerShell are generally designed for brevity. These shorter names can be typed quickly, but are impossible to read if you do not know what they refer to.

Windows PowerShell tries to compromise between clarity and brevity by providing a set of standard aliases that are based on shorthand names for common verbs and nouns. This allows a core set of aliases for common cmdlets that are readable when you know the shorthand names. For example, in standard aliases the verb Get is abbreviated to g, the verb Set is abbreviated to s, the noun Item is abbreviated to i, the noun Location is abbreviated to l, and the noun Command is abbreviated to cm.

Here is a brief example to illustrate how this works. The standard alias for Get-Item comes from combining g for Get and i for Item: gi. The standard alias for Set-Item comes from combining s for Set and i for Item: si. The standard alias for Get-Location comes from combining g for Get and l for Location, gl. The standard alias for Set-Location comes from combining s for Set and l for Location, sl. The standard alias for Get-Command comes from combining g for Get and cm for Command, gcm. There is no Set-Command cmdlet, but if there were, we would be able to guess that the standard alias comes from s for Set and cm for Command: scm. Furthermore, people familiar with Windows PowerShell aliasing who encounter scm would be able to guess that the alias refers to Set-Command.

Creating New Aliases

You can create your own aliases using the Set-Alias cmdlet. For example, the following statements create the standard cmdlet aliases discussed in Interpreting Standard Aliases:

Set-Alias -Name gi -Value Get-Item
Set-Alias -Name si -Value Set-Item
Set-Alias -Name gl -Value Get-Location
Set-Alias -Name sl -Value Set-Location
Set-Alias -Name gcm -Value Get-Command

Internally, Windows PowerShell uses commands like these during startup, but these aliases are not changeable. If you attempt to actually execute one of these commands, you will get an error explaining that the alias cannot be modified. For example:

PS> Set-Alias -Name gi -Value Get-Item

Set-Alias : Alias is not writeable because alias gi is read-only or constant and cannot be written to.

At line:1 char:10

+ Set-Alias <<<< -Name gi -Value Get-Item


Using Tab Expansion

Command-line shells often provide a way to complete the names of long files or commands automatically, speeding up command entry and providing hints. Windows PowerShell allows you to fill in file names and cmdlet names by pressing the Tab key.

Note:

Tab expansion is controlled by the internal function TabExpansion. Since this function can be modified or overridden, this discussion is a guide to the behavior of the default Windows PowerShell configuration.

To fill in a filename or path from the available choices automatically, type part of the name and press the Tab key. Windows PowerShell will automatically expand the name to the first match that it finds. Pressing the Tab key repeatedly will cycle through all of the available choices.

The tab expansion of cmdlet names is slightly different. To use tab expansion on a cmdlet name, type the entire first part of the name (the verb) and the hyphen that follows it. You can fill in more of the name for a partial match. For example, if you type get-co and then press the Tab key, Windows PowerShell will automatically expand this to the Get-Command cmdlet (notice that it also changes the case of letters to their standard form). If you press Tab key again, Windows PowerShell replaces this with the only other matching cmdlet name, Get-Content.

You can use tab expansion repeatedly on the same line. For example, you can use tab expansion on the name of the Get-Content cmdlet by entering:

PS> Get-Con<Tab>

When you press the Tab key, the command expands to:

PS> Get-Content

You can then partially specify the path to the Active Setup log file and use tab expansion again:

PS> Get-Content c:\windows\acts<Tab>

When you press the Tab key, the command expands to:

PS> Get-Content C:\windows\actsetup.log
Note:

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


Object Pipeline

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

Pipelines are arguably the most valuable concept used in command-line interfaces. Properly used, pipelines not only reduce the effort involved in entering complex commands, but also make it easier to see the flow of work in the commands. A related useful characteristic of pipelines is that because they operate on each item separately, you do not have to modify them based on whether you will have zero, one, or many items in the pipeline. Furthermore, each command in a pipeline (called a pipeline element) usually passes its output to the next command in the pipeline item-by-item. This usually reduces the resource demand of complex commands and allows you to begin getting the output immediately.

In this chapter, we will describe how the Windows PowerShell pipeline differs from the pipelines of most popular shells, and then demonstrate some basic tools that you can use to help control pipeline output and also to see how the pipeline operates.


Understanding the Windows PowerShell Pipeline

Piping works virtually everywhere in Windows PowerShell. Although you see text on the screen, Windows PowerShell does not pipe text between commands. Instead, it pipes objects.

The notation used for pipelines is similar to that used in other shells, so at first glance, it may not be apparent that Windows PowerShell introduces something new. For example, if you use the Out-Host cmdlet to force a page-by-page display of output from another command, the output looks just like the normal text displayed on the screen, broken up into pages:

PS> Get-ChildItem -Path C:\WINDOWS\System32 | Out-Host -Paging

    Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\WINDOWS\system32

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2005-10-22  11:04 PM        315 $winnt$.inf
-a---        2004-08-04   8:00 AM      68608 access.cpl
-a---        2004-08-04   8:00 AM      64512 acctres.dll
-a---        2004-08-04   8:00 AM     183808 accwiz.exe
-a---        2004-08-04   8:00 AM      61952 acelpdec.ax
-a---        2004-08-04   8:00 AM     129536 acledit.dll
-a---        2004-08-04   8:00 AM     114688 aclui.dll
-a---        2004-08-04   8:00 AM     194048 activeds.dll
-a---        2004-08-04   8:00 AM     111104 activeds.tlb
-a---        2004-08-04   8:00 AM       4096 actmovie.exe
-a---        2004-08-04   8:00 AM     101888 actxprxy.dll
-a---        2003-02-21   6:50 PM     143150 admgmt.msc
-a---        2006-01-25   3:35 PM      53760 admparse.dll
<SPACE> next page; <CR> next line; Q quit
...

The Out-Host -Paging command is a useful pipeline element whenever you have lengthy output that you would like to display slowly. It is especially useful if the operation is very CPU-intensive. Because processing is transferred to the Out-Host cmdlet when it has a complete page ready to display, cmdlets that precede it in the pipeline halt operation until the next page of output is available. You can see this if you use the Windows Task Manager to monitor CPU and memory use by Windows PowerShell.

Run the following command: Get-ChildItem C:\Windows -Recurse. Compare the CPU and memory usage to this command: Get-ChildItem C:\Windows -Recurse | Out-Host -Paging. What you see on the screen is text, but that is because it is necessary to represent objects as text in a console window. This is just a representation of what is really going on inside Windows PowerShell. For example, consider the Get-Location cmdlet. If you type Get-Location while your current location is the root of the C drive, you would see the following output:

PS> Get-Location

Path
----
C:\

If Windows PowerShell pipelined text, issuing a command such as Get-Location | Out-Host, would pass from Get-Location to Out-Host a set of characters in the order they are displayed onscreen. In other words, if you were to ignore the heading information, Out-Host would first receive the character 'C', then the character ':', then the character '\'. The Out-Host cmdlet could not determine what meaning to associate with the characters output by the Get-Location cmdlet.

Instead of using text to let commands in a pipeline communicate, Windows PowerShell uses objects. From the standpoint of a user, objects package related information into a form that makes it easier to manipulate the information as a unit, and extract specific items that you need.

The Get-Location command does not return text that contains the current path. It returns a package of information called a PathInfo object that contains the current path along with some other information. The Out-Host cmdlet then sends this PathInfo object to the screen, and Windows PowerShell decides what information to display and how to display it based on its formatting rules.

In fact, the heading information output by the Get-Location cmdlet is added only at the end of the process, as part of the process of formatting the data for onscreen display. What you see onscreen is a summary of information, and not a complete representation of the output object.

Given that there may be more information output from a Windows PowerShell command than what we see displayed in the console window, how can you retrieve the non-visible elements? How do you view the extra data? And what if you want to view the data in a format different than the one Windows PowerShell normally uses?

The rest of this chapter discusses how you can discover the structure of specific Windows PowerShell objects, selecting specific items and formatting them for easier display, and how to send this information to alternative output locations such as files and printers.


Viewing Object Structure (Get-Member)

Because objects play such a central role in Windows PowerShell, there are several native commands designed to work with arbitrary object types. The most important one is the Get-Member command.

The simplest technique for analyzing the objects that a command returns is to pipe the output of that command to the Get-Member cmdlet. The Get-Member cmdlet shows you the formal name of the object type and a complete listing of its members. The number of elements that are returned can sometimes be overwhelming. For example, a process object can have over 100 members.

To see all the members of a Process object and page the output so you can view all of it, type:

PS> Get-Process | Get-Member | Out-Host -Paging

The output from this command will look something like this:

   TypeName: System.Diagnostics.Process

Name                           MemberType     Definition
----                           ----------     ----------
Handles                        AliasProperty  Handles = Handlecount
Name                           AliasProperty  Name = ProcessName
NPM                            AliasProperty  NPM = NonpagedSystemMemorySize
PM                             AliasProperty  PM = PagedMemorySize
VM                             AliasProperty  VM = VirtualMemorySize
WS                             AliasProperty  WS = WorkingSet
add_Disposed                   Method         System.Void add_Disposed(Event...
...

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

PS> Get-Process | Get-Member -MemberType Properties

   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
Name                       AliasProperty  Name = ProcessName
...
ExitCode                   Property       System.Int32 ExitCode {get;}
...
Handle                     Property       System.IntPtr Handle {get;}
...
CPU                        ScriptProperty System.Object CPU {get=$this.Total...
...
Path                       ScriptProperty System.Object Path {get=$this.Main...
...
Note:

The allowed values of MemberType are AliasProperty, CodeProperty, Property, NoteProperty, ScriptProperty, Properties, PropertySet, Method, CodeMethod, ScriptMethod, Methods, ParameterizedProperty, MemberSet, and All.

There are over 60 properties for a process. The reason Windows PowerShell often shows only a handful of properties for any well-known object is that showing all of them would produce an unmanageable amount of information.

Note:

Windows PowerShell determines how to display an object type by using information stored in XML files that have names ending in .format.ps1xml. The formatting data for process objects, which are .NET System.Diagnostics.Process objects, is stored in PowerShellCore.format.ps1xml.

If you need to look at properties other than those that Windows PowerShell displays by default, you will need to format the output data yourself. This can be done by using the format cmdlets.


Using Format Commands to Change Output View

Windows PowerShell has a set of cmdlets that allow you to control which properties are displayed for particular objects. The names of all the cmdlets begin with the verb Format. They let you select one or more properties to show.

The Format cmdlets are Format-Wide, Format-List, Format-Table, and Format-Custom. We will only describe the Format-Wide, Format-List, and Format-Table cmdlets in this user's guide.

Each format cmdlet has default properties that will be used if you do not specify specific properties to display. Each cmdlet also uses the same parameter name, Property, to specify which properties you want to display. Because Format-Wide only shows a single property, its Property parameter only takes a single value, but the property parameters of Format-List and Format-Table will accept a list of property names.

If you use the command Get-Process -Name powershell with two instances of Windows PowerShell running, you get output that looks like this:

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    995       9    30308      27996   152     2.73   2760 powershell
    331       9    23284      29084   143     1.06   3448 powershell

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

Using Format-Wide for Single-Item Output

The Format-Wide cmdlet, by default, displays only the default property of an object. The information associated with each object is displayed in a single column:

PS> Get-Process -Name powershell | Format-Wide

powershell                              powershell

You can also specify a non-default property:

PS> Get-Process -Name powershell | Format-Wide -Property Id

2760                                    3448

Controlling Format-Wide Display with Column

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

Get-Command Format-Wide -Property Name -Column 1

Using Format-List for a List View

The Format-List cmdlet displays an object in the form of a listing, with each property labeled and displayed on a separate line:

PS> Get-Process -Name powershell | Format-List

Id      : 2760
Handles : 1242
CPU     : 3.03125
Name    : powershell

Id      : 3448
Handles : 328
CPU     : 1.0625
Name    : powershell

You can specify as many properties as you want:

PS> Get-Process -Name powershell | Format-List -Property ProcessName,FileVersion
,StartTime,Id

ProcessName : powershell
FileVersion : 1.0.9567.1
StartTime   : 2006-05-24 13:42:00
Id          : 2760

ProcessName : powershell
FileVersion : 1.0.9567.1
StartTime   : 2006-05-24 13:54:28
Id          : 3448

Getting Detailed Information by Using Format-List with Wildcards

The Format-List cmdlet lets you use a wildcard as the value of its Property parameter. This lets you display detailed information. Often, objects include more information than you need, which is why Windows PowerShell does not show all property values by default. To show all of properties of an object, use the Format-List -Property * command. The following command generates over 60 lines of output for a single process:

Get-Process -Name powershell | Format-List -Property *

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

Using Format-Table for Tabular Output

If you use the Format-Table cmdlet with no property names specified to format the output of the Get-Process command, you get exactly the same output as you do without performing any formatting. The reason is that processes are usually displayed in a tabular format, as are most Windows PowerShell objects.

PS> Get-Process -Name powershell | Format-Table

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
   1488       9    31568      29460   152     3.53   2760 powershell
    332       9    23140        632   141     1.06   3448 powershell

Improving Format-Table Output (AutoSize)

Although a tabular view is useful for displaying a lot of comparable information, it may be difficult to interpret if the display is too narrow for the data. For example, if you try to display process path, ID, name, and company, you get truncated output for the process path and the company column:

PS> Get-Process -Name powershell | Format-Table -Property Path,Name,Id,Company

Path                Name                                 Id Company
----                ----                                 -- -------
C:\Program Files... powershell                         2836 Microsoft Corpor...

If you specify the AutoSize parameter when you run the Format-Table command, Windows PowerShell will calculate column widths based on the actual data you are going to display. This makes the Path column readable, but the company column remains truncated:

PS> Get-Process -Name powershell | Format-Table -Property Path,Name,Id,Company -
AutoSize

Path                                                    Name         Id Company
----                                                    ----         -- -------
C:\Program Files\Windows PowerShell\v1.0\powershell.exe powershell 2836 Micr...

The Format-Table cmdlet might still truncate data, but it will only do so at the end of the screen. Properties, other than the last one displayed, are given as much size as they need for their longest data element to display correctly. You can see that company name is visible but path is truncated if you swap the locations of Path and Company in the Property value list:

PS> Get-Process -Name powershell | Format-Table -Property Company,Name,Id,Path -
AutoSize

Company               Name         Id Path
-------               ----         -- ----
Microsoft Corporation powershell 2836 C:\Program Files\Windows PowerShell\v1...

The Format-Table command assumes that the nearer a property is to the beginning of the property list, the more important it is. So it attempts to display the properties nearest the beginning completely. If the Format-Table command cannot display all the properties, it will remove some columns from the display and provide a warning. You can see this behavior if you make Name the last property in the list:

PS> Get-Process -Name powershell | Format-Table -Property Company,Path,Id,Name -
AutoSize

WARNING: column "Name" does not fit into the display and was removed.

Company               Path                                                    I
                                                                              d
-------               ----                                                    -
Microsoft Corporation C:\Program Files\Windows PowerShell\v1.0\powershell.exe 6

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

Wrapping Format-Table Output in Columns (Wrap)

You can force lengthy Format-Table data to wrap within its display column by using the Wrap parameter. Using the Wrap parameter alone will not necessarily do what you expect, since it uses default settings if you do not also specify AutoSize:

PS> Get-Process -Name powershell | Format-Table -Wrap -Property Name,Id,Company,
Path

Name                                 Id Company             Path
----                                 -- -------             ----
powershell                         2836 Microsoft Corporati C:\Program Files\Wi
                                        on                  ndows PowerShell\v1
                                                            .0\powershell.exe

An advantage of using the Wrap parameter by itself is that it does not slow down processing very much. If you perform a recursive file listing of a large directory system, it might take a very long time and use a lot of memory before displaying the first output items if you use AutoSize.

If you are not concerned about system load, then AutoSize works well with the Wrap parameter. The initial columns are always allotted as much width as they need to display items on one line, just as when you specify AutoSize without the Wrap parameter. The only difference is that the final column will be wrapped if necessary:

PS> Get-Process -Name powershell | Format-Table -Wrap -AutoSize -Property Name,I
d,Company,Path

Name         Id Company               Path
----         -- -------               ----
powershell 2836 Microsoft Corporation C:\Program Files\Windows PowerShell\v1.0\
                                      powershell.exe

Some columns might not be displayed if you specify the widest columns first, so it is safest to specify the smallest data elements first. In the following example, we specify the extremely wide path element first, and even with wrapping, we still lose the final Name column:

 PS> Get-Process -Name powershell | Format-Table -Wrap -AutoSize -Property Path,I
d,Company,Name

WARNING: column "Name" does not fit into the display and was removed.

Path                                                      Id Company
----                                                      -- -------
C:\Program Files\Windows PowerShell\v1.0\powershell.exe 2836 Microsoft Corporat
                                                             ion

Organizing Table Output (-GroupBy)

Another useful parameter for tabular output control is GroupBy. Longer tabular listings in particular may be hard to compare. The GroupBy parameter groups output based on a property value. For example, we can group processes by company for easier inspection, omitting the company value from the property listing:

PS> Get-Process -Name powershell | Format-Table -Wrap -AutoSize -Property Name,I
d,Path -GroupBy Company

   Company: Microsoft Corporation

Name         Id Path
----         -- ----
powershell 1956 C:\Program Files\Windows PowerShell\v1.0\powershell.exe
powershell 2656 C:\Program Files\Windows PowerShell\v1.0\powershell.exe


Redirecting Data with Out-* Cmdlets

Windows PowerShell provides several cmdlets that let you control data output directly. These cmdlets share two important characteristics.

First, they generally transform data to some form of text. They do this because they output the data to system components that require text input. This means they need to represent the objects as text. Therefore, the text is formatted as you see it in the Windows PowerShell console window.

Second, these cmdlets use the Windows PowerShell verb Out because they send information out from Windows PowerShell to somewhere else. The Out-Host cmdlet is no exception: the host window display is outside of Windows PowerShell. This is important because when data is sent out of Windows PowerShell, it is actually removed. You can see this if you try to create a pipeline that pages data to the host window, and then attempt to format it as a list, as shown here:

PS> Get-Process | Out-Host -Paging | Format-List

You might expect the command to display pages of process information in list format. Instead, it displays the default tabular list:

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    101       5     1076       3316    32     0.05   2888 alg
...
    618      18    39348      51108   143   211.20    740 explorer
    257       8     9752      16828    79     3.02   2560 explorer
...
<SPACE> next page; <CR> next line; Q quit
...

The Out-Host cmdlet sends the data directly to the console, so the Format-List command never receives anything to format.

The correct way to structure this command is to put the Out-Host cmdlet at the end of the pipeline as shown below. This causes the process data to be formatted in a list before being paged and displayed.

PS> Get-Process | Format-List | Out-Host -Paging

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

Id      : 740
Handles : 612
CPU     : 211.703125
Name    : explorer

Id      : 2560
Handles : 257
CPU     : 3.015625
Name    : explorer
...
<SPACE> next page; <CR> next line; Q quit
...

This applies to all of the Out cmdlets. An Out cmdlet should always appear at the end of the pipeline.

Note:

All the Out cmdlets render output as text, using the formatting in effect for the console window, including line length limits.

Paging Console Output (Out-Host)

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

PS> Get-Command | Out-Host -Paging

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

PS> Get-Command | more

If you include one or more filenames as arguments to the more function, the function will read the specified files and page their contents to the host:

PS> more c:\boot.ini
[boot loader]
timeout=5
default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
[operating systems]
...

Discarding Output (Out-Null)

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

PS> Get-Command | Out-Null

The Out-Null cmdlet does not discard error output. For example, if you enter the following command, a message is displayed informing you that Windows PowerShell does not recognize 'Is-NotACommand':

PS> Get-Command Is-NotACommand | Out-Null
Get-Command : 'Is-NotACommand' is not recognized as a cmdlet, function, operabl
e program, or script file.
At line:1 char:12
+ Get-Command  <<<< Is-NotACommand | Out-Null

Printing Data (Out-Printer)

You can print data by using the Out-Printer cmdlet. The Out-Printer cmdlet will use your default printer if you do not provide a printer name. You can use any Windows-based printer by specifying its display name. There is no need for any kind of printer port mapping or even a real physical printer. For example, if you have the Microsoft Office document imaging tools installed, you can send the data to an image file by typing:

PS> Get-Command Get-Command | Out-Printer -Name "Microsoft Office Document Image Writer"

Saving Data (Out-File)

You can send output to a file instead of the console window by using the Out-File cmdlet. The following command line sends a list of processes to the file C:\temp\processlist.txt:

PS> Get-Process | Out-File -FilePath C:\temp\processlist.txt

The results of using the Out-File cmdlet may not be what you expect if you are used to traditional output redirection. To understand its behavior, you must be aware of the context in which the Out-File cmdlet operates.

By default, the Out-File cmdlet creates a Unicode file. This is the best default in the long run, but it means that tools that expect ASCII files will not work correctly with the default output format. You can change the default output format to ASCII by using the Encoding parameter:

PS> Get-Process | Out-File -FilePath C:\temp\processlist.txt -Encoding ASCII

Out-file formats file contents to look like console output. This causes the output to be truncated just as it is in a console window in most circumstances. For example, if you run the following command:

PS> Get-Command | Out-File -FilePath c:\temp\output.txt

The output will look like this:

CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Add-Content                     Add-Content [-Path] <String[...
Cmdlet          Add-History                     Add-History [[-InputObject] ...
...

To get output that does not force line wraps to match the screen width, you can use the Width parameter to specify line width. Because Width is a 32-bit integer parameter, the maximum value it can have is 2147483647. Type the following to set the line width to this maximum value:

Get-Command | Out-File -FilePath c:\temp\output.txt -Width 2147483647

The Out-File cmdlet is most useful when you want to save output as it would have displayed on the console. For finer control over output format, you need more advanced tools. We will look at those in the next chapter, along with some details about object manipulation.


Windows PowerShell Navigation

Folders are a familiar organizational feature of the Windows Explorer interface, Cmd.exe, and UNIX tools such as BASH. Folders, or directories as they are more commonly known, are a useful concept for organizing files and other directories. UNIX-family operating systems extend this by treating everything possible as a file; specific hardware and network connections appear as files within particular folders. This approach does not ensure that the content is readable or usable by particular applications, but it does make it simpler to find specific items. Tools that enumerate or search through files and folders work with these devices as well. You can also address a specific item by using the path to the file that represents it.

Analogously, the Windows PowerShell infrastructure supports exposing virtually anything that can be navigated like a standard Microsoft Windows disk drive or a UNIX filesystem as a Windows PowerShell Drive. A Windows PowerShell Drive does not necessarily represent a real drive, either locally or on the network. This chapter primarily discusses navigation for file systems, but the concepts apply to Windows PowerShell Drives that are not associated with file systems.


Managing Current Location

When navigating folder systems in Windows Explorer, you usually have a specific working location - namely, the current open folder. Items in the current folder can be manipulated easily by clicking them. For command-line interfaces such as Cmd.exe, when you are in the same folder as a particular file, you can access it by specifying a relatively short name, rather than needing to specify the entire path to the file. The current directory is called the working directory.

Windows PowerShell uses the noun Location to refer to the working directory, and implements a family of cmdlets to examine and manipulate your location.

Getting Your Current Location (Get-Location)

To determine the path of your current directory location, enter the Get-Location command:

PS> Get-Location
Path
----
C:\Documents and Settings\PowerUser
Note:

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

Setting Your Current Location (Set-Location)

The Get-Location command is used with the Set-Location command. The Set-Location command allows you to specify your current directory location.

PS> Set-Location -Path C:\Windows

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

PS> Set-Location -Path C:\Windows -PassThru
Path
----
C:\WINDOWS

The -PassThru parameter can be used with many Set commands in Windows PowerShell to return information about the result in cases in which there is no default output.

You can specify paths relative to your current location in the same way as you would in most UNIX and Windows command shells. In standard notation for relative paths, a period (.)represents your current folder, and a doubled period (..) represents the parent directory of your current location.

For example, if you are in the C:\Windows folder, a period (.)represents C:\Windows and double periods (..) represent C:. You can change from your current location to the root of the C: drive by typing:

PS> Set-Location -Path .. -PassThru

Path

----

C:\

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

 PS> Set-Location -Path HKLM:\SOFTWARE -PassThru

Path
----
HKLM:\SOFTWARE

You can then change the directory location to the parent directory, which is the root of the Windows PowerShell HKLM: drive, by using a relative path:

PS> Set-Location -Path .. -PassThru

Path
----
HKLM:\

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

cd -Path C:\Windows

chdir -Path .. -PassThru

sl -Path HKLM:\SOFTWARE -PassThru

Saving and Recalling Recent Locations (Push-Location and Pop-Location)

When changing locations, it is helpful to keep track of where you have been and to be able to return to your previous location. The Push-Location cmdlet in Windows PowerShell creates a ordered history (a "stack") of directory paths where you have been, and you can step back through the history of directory paths by using the complementary Pop-Location cmdlet.

For example, Windows PowerShell typically starts in the user's home directory.

 PS> Get-Location

Path
----
C:\Documents and Settings\PowerUser
Note:

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

To push the current location onto the stack, and then move to the Local Settings folder, type:

 PS> Push-Location -Path "Local Settings"

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

PS> Push-Location -Path Temp

You can verify that you changed directories by entering the Get-Location command:

PS> Get-Location

Path
----
C:\Documents and Settings\PowerUser\Local Settings\Temp

You can then pop back into the most recently visited directory by entering the Pop-Location command, and verify the change by entering the Get-Location command:

PS> Pop-Location
PS> Get-Location

Path
----
C:\Documents and Settings\me\Local Settings

Just as with the Set-Location cmdlet, you can include the -PassThru parameter when you enter the Pop-Location cmdlet to display the directory that you entered:

PS> Pop-Location -PassThru

Path
----
C:\Documents and Settings\PowerUser

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

Set-Location \\FS01\Public

or

Push-Location \\FS01\Public

You can use the Push-Location and Set-Location commands to change the location to any available drive. For example, if you have a local CD-ROM drive with drive letter D that contains a data CD, you can change the location to the CD drive by entering the Set-Location D: command.

If the drive is empty, you will get the following error message:

PS> Set-Location D:
Set-Location : Cannot find path 'D:\' because it does not exist.

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


Managing Windows PowerShell Drives

A Windows PowerShell drive is a data store location that you can access like a file system drive in Windows PowerShell. The Windows PowerShell providers create some drives for you, such as the file system drives (including C: and D:), the registry drives (HKCU: and HKLM:), and the certificate drive (Cert:), and you can create your own Windows PowerShell drives. These drives are very useful, but they are available only within Windows PowerShell. You cannot access them by using other Windows tools, such as Windows Explorer or Cmd.exe.

Windows PowerShell uses the noun, PSDrive, for commands that work with Windows PowerShell drives. For a list of the Windows PowerShell drives in your Windows PowerShell session, use the Get-PSDrive cmdlet.

PS> Get-PSDrive

Name       Provider      Root                                   CurrentLocation
----       --------      ----                                   ---------------
A          FileSystem    A:\
Alias      Alias
C          FileSystem    C:\                                 ...And Settings\me
cert       Certificate   \
D          FileSystem    D:\
Env        Environment
Function   Function
HKCU       Registry      HKEY_CURRENT_USER
HKLM       Registry      HKEY_LOCAL_MACHINE
Variable   Variable

Although the drives in the display vary with the drives on your system, the listing will look similar to the output of the Get-PSDrive command shown above.

File system drives are a subset of the Windows PowerShell drives. You can identify the file system drives by the FileSystem entry in the Provider column. (The file system drives in Windows PowerShell are supported by the Windows PowerShell FileSystem provider.)

To see the syntax of the Get-PSDrive cmdlet, type a Get-Command command with the Syntax parameter:

PS> Get-Command -Name Get-PSDrive -Syntax
Get-PSDrive [[-Name] <String[]>] [-Scope <String>] [-PSProvider <String[]>] [-V
erbose] [-Debug] [-ErrorAction <ActionPreference>] [-ErrorVariable <String>] [-
OutVariable <String>] [-OutBuffer <Int32>]

The PSProvider parameter lets you display only the Windows PowerShell drives that are supported by a particular provider. For example, to display only the Windows PowerShell drives that are supported by the Windows PowerShell FileSystem provider, type a Get-PSDrive command with the PSProvider parameter and the FileSystem value:

PS> Get-PSDrive -PSProvider FileSystem

Name       Provider      Root                                   CurrentLocation
----       --------      ----                                   ---------------
A          FileSystem    A:\
C          FileSystem    C:\                           ...nd Settings\PowerUser
D          FileSystem    D:\

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

PS> Get-PSDrive -PSProvider Registry

Name Provider Root CurrentLocation

---- -------- ---- ---------------

HKCU Registry HKEY_CURRENT_USER

HKLM Registry HKEY_LOCAL_MACHINE

You can also use the standard Location cmdlets with the Windows PowerShell drives:

PS> Set-Location HKLM:\SOFTWARE

PS> Push-Location .\Microsoft

PS> Get-Location

Path

----

HKLM:\SOFTWARE\Microsoft

Adding New Windows PowerShell Drives (New-PSDrive)

You can add your own Windows PowerShell drives by using the New-PSDrive command. To get the syntax for the New-PSDrive command, enter the Get-Command command with the Syntax parameter:

PS> Get-Command -Name New-PSDrive -Syntax
New-PSDrive [-Name] <String> [-PSProvider] <String> [-Root] <String> [-Descript
ion <String>] [-Scope <String>] [-Credential <PSCredential>] [-Verbose] [-Debug
] [-ErrorAction <ActionPreference>] [-ErrorVariable <String>] [-OutVariable <St
ring>] [-OutBuffer <Int32>] [-WhatIf] [-Confirm]

To create a new Windows PowerShell drive, you must supply three parameters:

  • A name for the drive (you can use any valid Windows PowerShell name)

  • The PSProvider (use "FileSystem" for file system locations and "Registry" for registry locations)

  • The root, that is, the path to the root of the new drive

For example, you can create a drive named "Office" that is mapped to the folder that contains the Microsoft Office applications on your computer, such as C:\Program Files\Microsoft Office\OFFICE11. To create the drive, type the following command:

PS> New-PSDrive -Name Office -PSProvider FileSystem -Root "C:\Program Files\Micr
osoft Office\OFFICE11"

Name       Provider      Root                                   CurrentLocation
----       --------      ----                                   ---------------
Office     FileSystem    C:\Program Files\Microsoft Offic...
Note:

In general, paths are not case-sensitive.

You refer to the new Windows PowerShell drive as you do all Windows PowerShell drives -- by its name followed by a colon (:).

A Windows PowerShell drive can make many tasks much simpler. For example, some of the most important keys in the Windows registry have extremely long paths, making them cumbersome to access and difficult to remember. Critical configuration information resides under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion. To view and change items in the CurrentVersion registry key, you can create a Windows PowerShell drive that is rooted in that key by typing:

PS> New-PSDrive -Name cvkey -PSProvider Registry -Root HKLM\Software\Microsoft\W

indows\CurrentVersion

Name Provider Root CurrentLocation

---- -------- ---- ---------------

cvkey Registry HKLM\Software\Microsoft\Windows\...

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

PS> cd cvkey:

or:

PS> Set-Location cvkey: -PassThru

Path

----

cvkey:\

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

Deleting Windows PowerShell Drives (Remove-PSDrive)

You can delete drives from Windows PowerShell by using the Remove-PSDrive cmdlet. The Remove-PSDrive cmdlet is easy to use; to delete a specific Windows PowerShell drive, you just supply the Windows PowerShell drive name.

For example, if you added the Office: Windows PowerShell drive, as shown in the New-PSDrive topic, you can delete it by typing:

PS> Remove-PSDrive -Name Office

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

PS> Remove-PSDrive -Name cvkey

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

PS> cd office:
PS Office:\> remove-psdrive -name office
Remove-PSDrive : Cannot remove drive 'Office' because it is in use.
At line:1 char:15
+ remove-psdrive  <<<< -name office

Adding and Removing Drives Outside Windows PowerShell

Windows PowerShell detects file system drives that are added or removed in Windows, including network drives that are mapped, USB drives that are attached, and drives that are deleted by using either the net use command or the WScript.Network MapNetworkDrive and RemoveNetworkDrive methods from a Windows Script Host (WSH) script.


Working With Files, Folders and Registry Keys

Windows PowerShell uses the noun Item to refer to items found on a Windows PowerShell drive. When dealing with the Windows PowerShell FileSystem provider, an Item might be a file, a folder, or the Windows PowerShell drive. Listing and working with these items is a critical basic task in most administrative settings, so we want to discuss these tasks in detail.

Enumerating Files, Folders, and Registry Keys (Get-ChildItem)

Since getting a collection of items from a particular location is such a common task, the Get-ChildItem cmdlet is designed specifically to return all items found within a container such as a folder.

If you want to return all files and folders that are contained directly within the folder C:\Windows, type:

PS> Get-ChildItem -Path C:\Windows
    Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\Windows
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2006-05-16   8:10 AM          0 0.log
-a---        2005-11-29   3:16 PM         97 acc1.txt
-a---        2005-10-23  11:21 PM       3848 actsetup.log
...

The listing looks similar to what you would see when you enter the dir command in Cmd.exe, or the ls command in a UNIX command shell.

You can perform very complex listings by using parameters of the Get-ChildItem cmdlet. We will look at a few scenarios next. You can see the syntax the Get-ChildItem cmdlet by typing:

PS> Get-Command -Name Get-ChildItem -Syntax

These parameters can be mixed and matched to get highly customized output.

Listing all Contained Items (-Recurse)

To see both the items inside a Windows folder and any items that are contained within the subfolders, use the Recurse parameter of Get-ChildItem. The listing displays everything within the Windows folder and the items in its subfolders. For example:

PS> Get-ChildItem -Path C:\WINDOWS -Recurse

    Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\WINDOWS
    Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\WINDOWS\AppPatch
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2004-08-04   8:00 AM    1852416 AcGenral.dll
...

Filtering Items by Name (-Name)

To display only the names of items, use the Name parameter of Get-Childitem:

PS> Get-ChildItem -Path C:\WINDOWS -Name
addins
AppPatch
assembly
...

Forcibly Listing Hidden Items (-Force)

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

Get-ChildItem -Path C:\Windows -Force

This parameter is named Force because you can forcibly override the normal behavior of the Get-ChildItem command. Force is a widely used parameter that forces an action that a cmdlet would not normally perform, although it will not perform any action that compromises the security of the system.

Matching Item Names with Wildcards

The Get-ChildItem command accepts wildcards in the path of the items to list.

Because wildcard matching is handled by the Windows PowerShell engine, all cmdlets that accepts wildcards use the same notation and have the same matching behavior. The Windows PowerShell wildcard notation includes:

  • Asterisk (*)matches zero or more occurrences of any character.

  • Question mark (?) matches exactly one character.

  • Left bracket ([) character and right bracket (]) character surround a set of characters to be matched.

Here are some examples of how wildcard specification works.

To find all files in the Windows directory with the suffix .log and exactly five characters in the base name, enter the following command:

PS> Get-ChildItem -Path C:\Windows\?????.log
    Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\Windows
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
...
-a---        2006-05-11   6:31 PM     204276 ocgen.log
-a---        2006-05-11   6:31 PM      22365 ocmsn.log
...
-a---        2005-11-11   4:55 AM         64 setup.log
-a---        2005-12-15   2:24 PM      17719 VxSDM.log
...

To find all files that begin with the letter x in the Windows directory, type:

 Get-ChildItem -Path C:\Windows\x*

To find all files whose names begin with x or z, type:

Get-ChildItem -Path C:\Windows\[xz]*

Excluding Items (-Exclude)

You can exclude specific items by using the Exclude parameter of Get-ChildItem. This lets you perform complex filtering in a single statement.

For example, suppose you are trying to find the Windows Time Service DLL in the System32 folder, and all you can remember about the DLL name is that it begins with "W" and has "32" in it.

An expression like w*32*.dll will find all DLLs that satisfy the conditions, but it may also return the Windows 95 and 16-bit Windows compatibility DLLs that include "95" or "16" in their names. You can omit files that have any of these numbers in their names by using the Exclude parameter with the pattern *[9516]*:

PS> Get-ChildItem -Path C:\WINDOWS\System32\w*32*.dll -Exclude *[9516]*

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

Mode LastWriteTime Length Name

---- ------------- ------ ----

-a--- 2004-08-04 8:00 AM 174592 w32time.dll

-a--- 2004-08-04 8:00 AM 22016 w32topl.dll

-a--- 2004-08-04 8:00 AM 101888 win32spl.dll

-a--- 2004-08-04 8:00 AM 172032 wldap32.dll

-a--- 2004-08-04 8:00 AM 264192 wow32.dll

-a--- 2004-08-04 8:00 AM 82944 ws2_32.dll

-a--- 2004-08-04 8:00 AM 42496 wsnmp32.dll

-a--- 2004-08-04 8:00 AM 22528 wsock32.dll

-a--- 2004-08-04 8:00 AM 18432 wtsapi32.dll

Mixing Get-ChildItem Parameters

You can use several of the parameters of the Get-ChildItem cmdlet in the same command. Before you mix parameters, be sure that you understand wildcard matching. For example, the following command returns no results:

PS> Get-ChildItem -Path C:\Windows\*.dll -Recurse -Exclude [a-y]*.dll

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

No results were returned because we specified the wildcard as part of the path. Even though the command was recursive, the Get-ChildItem cmdlet restricted the items to those that are in the Windows folder with names ending with ".dll".

To specify a recursive search for files whose names match a special pattern, use the -Include parameter.

PS> Get-ChildItem -Path C:\Windows -Include *.dll -Recurse -Exclude [a-y]*.dll

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

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2004-08-04   8:00 AM       8261 zoneoc.dll

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

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2004-08-04   8:00 AM     337920 zipfldr.dll


Manipulating Items Directly

The elements that you see in Windows PowerShell drives, such as the files and folders in the file system drives, and the registry keys in the Windows PowerShell registry drives, are called items in Windows PowerShell. The cmdlets for working with them item have the noun Item in their names.

The output of the Get-Command -Noun Item command shows that there are nine Windows PowerShell item cmdlets.

PS> Get-Command -Noun Item

CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Clear-Item                      Clear-Item [-Path] <String[]...
Cmdlet          Copy-Item                       Copy-Item [-Path] <String[]>...
Cmdlet          Get-Item                        Get-Item [-Path] <String[]> ...
Cmdlet          Invoke-Item                     Invoke-Item [-Path] <String[...
Cmdlet          Move-Item                       Move-Item [-Path] <String[]>...
Cmdlet          New-Item                        New-Item [-Path] <String[]> ...
Cmdlet          Remove-Item                     Remove-Item [-Path] <String[...
Cmdlet          Rename-Item                     Rename-Item [-Path] <String>...
Cmdlet          Set-Item                        Set-Item [-Path] <String[]> ...

Creating New Items (New-Item)

To create a new item in the file system, use the New-Item cmdlet. Include the Path parameter with path to the item, and the ItemType parameter with a value of "file" or "directory".

For example, to create a new directory named "New.Directory"in the C:\Temp directory, type:

PS> New-Item -Path c:\temp\New.Directory -ItemType Directory

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

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        2006-05-18  11:29 AM            New.Directory

To create a file, change the value of the ItemType parameter to "file". For example, to create a file named "file1.txt" in the New.Directory directory, type:

PS> New-Item -Path C:\temp\New.Directory\file1.txt -ItemType file

    Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\temp\New.Directory

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2006-05-18  11:44 AM          0 file1

You can use the same technique to create a new registry key. In fact, a registry key is easier to create because the only item type in the Windows registry is a key. (Registry entries are item properties.) For example, to create a key named "_Test" in the CurrentVersion subkey, type:

PS> New-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\_Test

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Micros
oft\Windows\CurrentVersion

SKC  VC Name                           Property
---  -- ----                           --------
  0   0 _Test                          {}

When typing a registry path, be sure to include the colon (:) in the Windows PowerShell drive names, HKLM: and HKCU:. Without the colon, Windows PowerShell does not recognize the drive name in the path.

Why Registry Values are not Items

When you use the Get-ChildItem cmdlet to find the items in a registry key, you will never see actual registry entries or their values.

For example, the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run usually contains several registry entries that represent applications that run when the system starts.

However, when you use Get-ChildItem to look for child items in the key, all you will see is the OptionalComponents subkey of the key:

PS> Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Run
   Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Micros
oft\Windows\CurrentVersion\Run
SKC  VC Name                           Property
---  -- ----                           --------
  3   0 OptionalComponents             {}

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

Renaming Existing Items (Rename-Item)

To change the name of a file or folder, use the Rename-Item cmdlet. The following command changes the name of the file1.txt file to fileOne.txt.

PS> Rename-Item -Path C:\temp\New.Directory\file1.txt fileOne.txt

The Rename-Item cmdlet can change the name of a file or a folder, but it cannot move an item. The following command fails because it attempts to move the file from the New.Directory directory to the Temp directory.

PS> Rename-Item -Path C:\temp\New.Directory\fileOne.txt c:\temp\fileOne.txt
Rename-Item : Cannot rename because the target specified is not a path.
At line:1 char:12
+ Rename-Item  <<<< -Path C:\temp\New.Directory\fileOne c:\temp\fileOne.txt

Moving Items (Move-Item)

To move a file or folder, use the Move-Item cmdlet.

For example, the following command moves the New.Directory directory from the C:\temp directory to the root of the C: drive. To verify that the item was moved, include the PassThru parameter of the Move-Item cmdlet. Without Passthru, the Move-Item cmdlet does not display any results.

PS> Move-Item -Path C:\temp\New.Directory -Destination C:\ -PassThru

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

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        2006-05-18  12:14 PM            New.Directory

Copying Items (Copy-Item)

If you are familiar with the copy operations in other shells, you might find the behavior of the Copy-Item cmdlet in Windows PowerShell to be unusual. When you copy an item from one location to another, Copy-Item does not copy its contents by default.

For example, if you copy the New.Directory directory from the C: drive to the C:\temp directory, the command succeeds, but the files in the New.Directory directory are not copied.

PS> Copy-Item -Path C:\New.Directory -Destination C:\temp

If you display the contents of C:\temp\New.Directory, you will find that it contains no files:

PS> Get-ChildItem -Path C:\temp\New.Directory
PS>

Why doesn't the Copy-Item cmdlet copy the contents to the new location?

The Copy-Item cmdlet was designed to be generic; it is not just for copying files and folders. Also, even when copying files and folders, you might want to copy only the container and not the items within it.

To copy all of the contents of a folder, include the Recurse parameter of the Copy-Item cmdlet in the command. If you have already copied the directory without its contents, add the Force parameter, which allows you to overwrite the empty folder.

PS> Copy-Item -Path C:\New.Directory -Destination C:\temp -Recurse -Force -Passthru
    Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\temp

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        2006-05-18   1:53 PM            New.Directory

    Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\temp\New.Directory

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2006-05-18  11:44 AM          0 file1

Deleting Items (Remove-Item)

To delete files and folders, use the Remove-Item cmdlet. Windows PowerShell cmdlets, such as Remove-Item, that can make significant, irreversible changes will often prompt for confirmation when you enter its commands. For example, if you try to remove the New.Directory folder, you will be prompted to confirm the command, because the folder contains files:

PS> Remove-Item C:\New.Directory

Confirm
The item at C:\temp\New.Directory has children and the -recurse parameter was not
specified. If you continue, all children will be removed with the item. Are you
 sure you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):

Because Yes is the default response, to delete the folder and its files, press the Enter key. To remove the folder without confirming, use the -Recurse parameter.

PS> Remove-Item C:\temp\New.Directory -Recurse

Executing Items (Invoke-Item)

Windows PowerShell uses the Invoke-Item cmdlet to perform a default action for a file or folder. This default action is determined by the default application handler in the registry; the effect is the same as if you double-click the item in Windows Explorer.

For example, suppose you run the following command:

PS> Invoke-Item C:\WINDOWS

An Explorer window that is located in C:\Windows appears, just as if you had double-clicked the C:\Windows folder.

If you invoke the Boot.ini file on a system prior to Windows Vista:

PS> Invoke-Item C:\boot.ini

If the .ini file type is associated with Notepad, the boot.ini file opens in Notepad.


Working with Objects

We have discussed how Windows PowerShell uses objects to transfer data between cmdlets, and demonstrated a few ways to view detailed information about objects by using Get-Member and Format cmdlets to view particular properties of objects.

The power of objects is that they provide you with access to a lot of complex data, and it is already correlated. With some simple techniques you can further manipulate objects to do even more work. We are going to look at some specific types of objects and ways you can manipulate them in this chapter.


Getting WMI Objects (Get-WmiObject)

Getting WMI Objects (Get-WmiObject)

Windows Management Instrumentation (WMI) is a core technology for Windows system administration because it exposes a wide range of information in a uniform manner. Because of how much WMI makes possible, the Windows PowerShell cmdlet for accessing WMI objects, Get-WmiObject, is one of the most useful for doing real work. We are going to discuss how to use Get-WmiObject to access WMI objects and then how to use WMI objects to do specific things.

Listing WMI Classes

The first problem most WMI users encounter is trying to find out what can be done with WMI. WMI classes describe the resources that can be managed. There are hundreds of WMI classes, some of which contain dozens of properties.

Get-WmiObject addresses this problem by making WMI discoverable. You can get a list of the WMI classes available on the local computer by typing:

PS> Get-WmiObject -List

__SecurityRelatedClass                  __NTLMUser9X
__PARAMETERS                            __SystemSecurity
__NotifyStatus                          __ExtendedStatus
Win32_PrivilegesStatus                  Win32_TSNetworkAdapterSettingError
Win32_TSRemoteControlSettingError       Win32_TSEnvironmentSettingError
...

You can retrieve the same information from a remote computer by using the ComputerName parameter, specifying a computer name or IP address:

PS> Get-WmiObject -List -ComputerName 192.168.1.29

__SystemClass                           __NAMESPACE
__Provider                              __Win32Provider
__ProviderRegistration                  __ObjectProviderRegistration
...

The class listing returned by remote computers may vary due to the specific operating system the computer is running and the particular WMI extensions added by installed applications.

Note:

When using Get-WmiObject to connect to a remote computer, the remote computer must be running WMI and, under the default configuration, the account you are using must be in the local administrators group on the remote computer. The remote system does not need to have Windows PowerShell installed. This allows you to administer operating systems that are not running Windows PowerShell, but do have WMI available.

You can even include the ComputerName when connecting to the local system. You can use the local computer's name, its IP address (or the loopback address 127.0.0.1), or the WMI-style '.' as the computer name. If you are running Windows PowerShell on a computer named Admin01 with IP address 192.168.1.90, the following commands will all return the WMI class listing for that computer:

Get-WmiObject -List
Get-WmiObject -List -ComputerName .
Get-WmiObject -List -ComputerName Admin01
Get-WmiObject -List -ComputerName 192.168.1.90
Get-WmiObject -List -ComputerName 127.0.0.1
Get-WmiObject -List -ComputerName localhost

Get-WmiObject uses the root/cimv2 namespace by default. If you want to specify another WMI namespace, use the Namespace parameter and specify the corresponding namespace path:

PS> Get-WmiObject -List -ComputerName 192.168.1.29 -Namespace root

__SystemClass                           __NAMESPACE
__Provider                              __Win32Provider
...

Displaying WMI Class Details

If you already know the name of a WMI class, you can use it to get information immediately. For example, one of the WMI classes commonly used for retrieving information about a computer is Win32_OperatingSystem.

PS> Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName .

SystemDirectory : C:\WINDOWS\system32
Organization    : Global Network Solutions
BuildNumber     : 2600
RegisteredUser  : Oliver W. Jones
SerialNumber    : 12345-678-9012345-67890
Version         : 5.1.2600

Although we are showing all of the parameters, the command can be expressed in a more succinct way. The ComputerName parameter is not necessary when connecting to the local system. We show it to demonstrate the most general case and remind you about the parameter. The Namespace defaults to root/cimv2, and can be omitted as well. Finally, most cmdlets allow you to omit the name of common parameters. With Get-WmiObject, if no name is specified for the first parameter, Windows PowerShell treats it as the Class parameter. This means the last command could have been issued by typing:

Get-WmiObject Win32_OperatingSystem

The Win32_OperatingSystem class has many more properties than those displayed here. You can use Get-Member to see all the properties. The properties of a WMI class are automatically available like other object properties:

PS> Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName . | Get-Member -MemberType Property

   TypeName: System.Management.ManagementObject#root\cimv2\Win32_OperatingSyste
m

Name                                      MemberType Definition
----                                      ---------- ----------
__CLASS                                   Property   System.String __CLASS {...
...
BootDevice                                Property   System.String BootDevic...
BuildNumber                               Property   System.String BuildNumb...
...

Displaying Non-Default Properties with Format Cmdlets

If you want information contained in the Win32_OperatingSystem class that is not displayed by default, you can display it by using the Format cmdlets. For example, if you want to display available memory data, type:

PS> Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName . | Format-Table -Property TotalVirtualMemorySize,TotalVisibleMemorySize,FreePhysicalMemory,FreeVirtualMemory,FreeSpaceInPagingFiles

TotalVirtualMemorySize TotalVisibleMem FreePhysicalMem FreeVirtualMemo FreeSpaceInPagi
                              ory              ry         ngFiles
--------------- --------------- --------------- --------------- ---------------
        2097024          785904          305808         2056724         1558232
Note:

Wildcards work with property names in Format-Table, so the final pipeline element can be reduced to Format-Table -Property TotalV*,Free*

The memory data might be more readable if you format it as a list by typing:

PS> Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName . | Format-List TotalVirtualMemorySize,TotalVisibleMemorySize,FreePhysicalMemory,FreeVirtualMemory,FreeSpaceInPagingFiles

TotalVirtualMemorySize : 2097024
TotalVisibleMemorySize : 785904
FreePhysicalMemory     : 301876
FreeVirtualMemory      : 2056724
FreeSpaceInPagingFiles : 1556644


Creating .NET and COM Objects (New-Object)

There are software components with .NET Framework and COM interfaces that enable you to perform many system administration tasks. Windows PowerShell lets you use these components, so you are not limited to the tasks that can be performed by using cmdlets. Many of the cmdlets in the initial release of Windows PowerShell do not work against remote computers. We will demonstrate how to get around this limitation when managing event logs by using the .NET Framework System.Diagnostics.EventLog class directly from Windows PowerShell.

Using New-Object for Event Log Access

The .NET Framework Class Library includes a class named System.Diagnostics.EventLog that can be used to manage event logs. You can create a new instance of a .NET Framework class by using the New-Object cmdlet with the TypeName parameter. For example, the following command creates an event log reference:

PS> New-Object -TypeName System.Diagnostics.EventLog

  Max(K) Retain OverflowAction        Entries Name
  ------ ------ --------------        ------- ----

Although the command has created an instance of the EventLog class, the instance does not include any data. That is because we did not specify a particular event log. How do you get a real event log?

Using Constructors with New-Object

To refer to a specific event log, you need to specify the name of the log. New-Object has an ArgumentList parameter. The arguments you pass as values to this parameter are used by a special startup method of the object. The method is called a constructor because it is used to construct the object. For example, to get a reference to the Application log, you specify the string 'Application' as an argument:

PS> New-Object -TypeName System.Diagnostics.EventLog -ArgumentList Application

Max(K) Retain OverflowAction        Entries Name
------ ------ --------------        ------- ----
16,384      7 OverwriteOlder          2,160 Application
Note:

Since most of the .NET Framework core classes are contained in the System namespace, Windows PowerShell will automatically attempt to find classes you specify in the System namespace if it cannot find a match for the typename you specify. This means that you can specify Diagnostics.EventLog instead of System.Diagnostics.EventLog.

Storing Objects in Variables

You might want to store a reference to an object, so you can use it in the current shell. Although Windows PowerShell lets you do a lot of work with pipelines, lessening the need for variables, sometimes storing references to objects in variables makes it more convenient to manipulate those objects.

Windows PowerShell lets you create variables that are essentially named objects. The output from any valid Windows PowerShell command can be stored in a variable. Variable names always begin with $. If you want to store the Application log reference in a variable named $AppLog, type the name of the variable, followed by an equal sign and then type the command used to create the Application log object:

PS> $AppLog = New-Object -TypeName System.Diagnostics.EventLog -ArgumentList Application

If you then type $AppLog, you can see that it contains the Application log:

PS> $AppLog

  Max(K) Retain OverflowAction        Entries Name
  ------ ------ --------------        ------- ----
  16,384      7 OverwriteOlder          2,160 Application

Accessing a Remote Event Log with New-Object

The commands used in the preceding section target the local computer; the Get-EventLog cmdlet can do that. To access the Application log on a remote computer, you must supply both the log name and a computer name (or IP address) as arguments.

PS> $RemoteAppLog = New-Object -TypeName System.Diagnostics.EventLog Application,192.168.1.81
PS> $RemoteAppLog

  Max(K) Retain OverflowAction        Entries Name
  ------ ------ --------------        ------- ----
     512      7 OverwriteOlder            262 Application

Now that we have a reference to an event log stored in the $RemoteAppLog variable, what tasks can we perform on it?

Clearing an Event Log with Object Methods

Objects often have methods that can be called to perform tasks. You can use Get-Member to display the methods associated with an object. The following command and selected output show some the methods of the EventLog class:

PS> $RemoteAppLog | Get-Member -MemberType Method

   TypeName: System.Diagnostics.EventLog

Name                      MemberType Definition
----                      ---------- ----------
...
Clear                     Method     System.Void Clear()
Close                     Method     System.Void Close()
...
GetType                   Method     System.Type GetType()
...
ModifyOverflowPolicy      Method     System.Void ModifyOverflowPolicy(Overfl...
RegisterDisplayName       Method     System.Void RegisterDisplayName(String ...
...
ToString                  Method     System.String ToString()
WriteEntry                Method     System.Void WriteEntry(String message),...
WriteEvent                Method     System.Void WriteEvent(EventInstance in...

The Clear() method can be used to clear the event log. When calling a method, you must always follow the method name by parentheses, even if the method does not require arguments. This lets Windows PowerShell distinguish between the method and a potential property with the same name. Type the following to call the Clear method:

PS> $RemoteAppLog.Clear()

Type the following to display the log. You will see that the event log was cleared, and now has 0 entries instead of 262:

PS> $RemoteAppLog

  Max(K) Retain OverflowAction        Entries Name
  ------ ------ --------------        ------- ----
     512      7 OverwriteOlder              0 Application

Creating COM Objects with New-Object

You can use New-Object to work with Component Object Model (COM) components. Components range from the various libraries included with Windows Script Host (WSH) to ActiveX applications such as Internet Explorer that are installed on most systems.

New-Object uses .NET Framework Runtime-Callable Wrappers to create COM objects, so it has the same limitations that .NET Framework does when calling COM objects. To create a COM object, you need to specify the ComObject parameter with the Programmatic Identifier or ProgId of the COM class you want to use. A complete discussion of the limitations of COM use and determining what ProgIds are available on a system is beyond the scope of this user's guide, but most well-known objects from environments such as WSH can be used within Windows PowerShell.

You can create the WSH objects by specifying these progids: WScript.Shell, WScript.Network, Scripting.Dictionary, and Scripting.FileSystemObject. The following commands create these objects:

New-Object -ComObject WScript.Shell
New-Object -ComObject WScript.Network
New-Object -ComObject Scripting.Dictionary
New-Object -ComObject Scripting.FileSystemObject

Although most of the functionality of these classes is made available in other ways in Windows PowerShell, a few tasks such as shortcut creation are still easier to do using the WSH classes.

Creating a Desktop Shortcut with WScript.Shell

One task that can be performed quickly with a COM object is creating a shortcut. Suppose you want to create a shortcut on your desktop that links to the home folder for Windows PowerShell. You first need to create a reference to WScript.Shell, which we will store in a variable named $WshShell:

$WshShell = New-Object -ComObject WScript.Shell

Get-Member works with COM objects, so you can explore the members of the object by typing:

PS> $WshShell | Get-Member

   TypeName: System.__ComObject#{41904400-be18-11d3-a28b-00104bd35090}

Name                     MemberType            Definition
----                     ----------            ----------
AppActivate              Method                bool AppActivate (Variant, Va...
CreateShortcut           Method                IDispatch CreateShortcut (str...
...

Get-Member has an optional InputObject parameter you can use instead of piping to provide input to Get-Member. You would get the same output as shown above if you instead used the command Get-Member -InputObject $WshShell. If you use InputObject, it treats its argument as a single item. This means that if you have several objects in a variable, Get-Member treats them as an array of objects. For example:

PS> $a = 1,2,"three"
PS> Get-Member -InputObject $a
TypeName: System.Object[]
Name               MemberType    Definition
----               ----------    ----------
Count              AliasProperty Count = Length
...

The WScript.Shell CreateShortcut method accepts a single argument, the path to the shortcut file to create. We could type in the full path to the desktop, but there is an easier way. The desktop is normally represented by a folder named Desktop inside the home folder of the current user. Windows PowerShell has a variable $Home that contains the path to this folder. We can specify the path to the home folder by using this variable, and then add the name of the Desktop folder and the name for the shortcut to create by typing:

$lnk = $WshShell.CreateShortcut("$Home\Desktop\PSHome.lnk")

When you use something that looks like a variable name inside double-quotes, Windows PowerShell tries to substitute a matching value. If you use single-quotes, Windows PowerShell does not try to substitute the variable value. For example, try typing the following commands:

PS> "$Home\Desktop\PSHome.lnk"
C:\Documents and Settings\aka\Desktop\PSHome.lnk
PS> '$Home\Desktop\PSHome.lnk'
$Home\Desktop\PSHome.lnk

We now have a variable named $lnk that contains a new shortcut reference. If you want to see its members, you can pipe it to Get-Member. The output below shows the members we need to use to finish creating our shortcut:

PS> $lnk | Get-Member

TypeName: System.__ComObject#{f935dc23-1cf0-11d0-adb9-00c04fd58a0b}

Name MemberType Definition

---- ---------- ----------

...

Save Method void Save ()

...

TargetPath Property string TargetPath () {get} {set}

...

We need to specify the TargetPath, which is the application folder for Windows PowerShell, and then save the shortcut $lnk by calling the Save method. The Windows PowerShell application folder path is stored in the variable $PSHome, so we can do this by typing:

$lnk.TargetPath = $PSHome

$lnk.Save()

Using Internet Explorer from Windows PowerShell

Many applications (including the Microsoft Office family of applications and Internet Explorer) can be automated by using COM. Internet Explorer illustrates some of the typical techniques and issues involved in working with COM-based applications.

You create an Internet Explorer instance by specifying the Internet Explorer ProgId, InternetExplorer.Application:

$ie = New-Object -ComObject InternetExplorer.Application

This command starts Internet Explorer, but does not make it visible. If you type Get-Process, you can see that a process named iexplore is running. In fact, if you exit Windows PowerShell, the process will continue to run. You must reboot the computer or use a tool like Task Manager to end the iexplore process.

Note:

COM objects that start as separate processes, commonly called ActiveX executables, may or may not display a user interface window when they start up. If they create a window but do not make it visible, like Internet Explorer, the focus will generally move to the Windows desktop and you must make the window visible to interact with it.

By typing $ie | Get-Member, you can view properties and methods for Internet Explorer. To see the Internet Explorer window, set the Visible property to $true by typing:

$ie.Visible = $true

You can then navigate to a specific Web address by using the Navigate method:

$ie.Navigate("http://www.microsoft.com/technet/scriptcenter/default.mspx")

Using other members of the Internet Explorer object model, it is possible to retrieve text content from the Web page. The following command will display the HTML text in the body of the current Web page:

$ie.Document.Body.InnerText

To close Internet Explorer from within PowerShell, call its Quit() method:

$ie.Quit()

This will force it to close. The $ie variable no longer contains a valid reference even though it still appears to be a COM object. If you attempt to use it, you will get an automation error:

PS> $ie | Get-Member
Get-Member : Exception retrieving the string representation for property "Appli
cation" : "The object invoked has disconnected from its clients. (Exception fro
m HRESULT: 0x80010108 (RPC_E_DISCONNECTED))"
At line:1 char:16
+ $ie | Get-Member <<<<

You can either remove the remaining reference with a command like $ie = $null, or completely remove the variable by typing:

Remove-Variable ie
Note:

There is no common standard for whether ActiveX executables exit or continue to run when you remove a reference to one. Depending on circumstances such as whether the application is visible, whether an edited document is running in it, and even whether Windows PowerShell is still running, the application may or may not exit. For this reason, you should test termination behavior for each ActiveX executable you want to use in Windows PowerShell.

Getting Warnings About .NET Framework-Wrapped COM Objects

In some cases, a COM object might have an associated .NET Framework Runtime-Callable Wrapper or RCW, and this will be used by New-Object. Since the behavior of the RCW may be different from the behavior of the normal COM object, New-Object has a Strict parameter to warn you about RCW access. If you specify the Strict parameter and then create a COM object that uses an RCW, you get a warning message:

PS> $xl = New-Object -ComObject Excel.Application -Strict
New-Object : The object written to the pipeline is an instance of the type "Mic
rosoft.Office.Interop.Excel.ApplicationClass" from the component's primary inte
rop assembly. If this type exposes different members than the IDispatch members
, scripts written to work with this object might not work if the primary intero
p assembly is not installed.
At line:1 char:17
+ $xl = New-Object  <<<< -ComObject Excel.Application -Strict

Although the object is still created, you are warned that it is not a standard COM object.


Using Static Classes and Methods

Not all .NET Framework classes can be created by using New-Object. For example, if you try to create a System.Environment or a System.Math object with New-Object, you will get the following error messages:

PS> New-Object System.Environment
New-Object : Constructor not found. Cannot find an appropriate constructor for
type System.Environment.
At line:1 char:11
+ New-Object  <<<< System.Environment
PS> New-Object System.Math
New-Object : Constructor not found. Cannot find an appropriate constructor for
type System.Math.
At line:1 char:11
+ New-Object  <<<< System.Math

These errors occur because there is no way to create a new object from these classes. These classes are reference libraries of methods and properties that do not change state. You don't need to create them, you simply use them. Classes and methods such as these are called static classes because they are not created, destroyed, or changed. To make this clear we will provide examples that use static classes.

Getting Environment Data with System.Environment

Usually, the first step in working with an object in Windows PowerShell is to use Get-Member to find out what members it contains. With static classes, the process is a little different because the actual class is not an object.

Referring to the Static System.Environment Class

You can refer to a static class by surrounding the class name with square brackets. For example, you can refer to System.Environment by typing the name within brackets. Doing so displays some generic type information:

PS> [System.Environment]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    Environment                              System.Object
Note:

As we mentioned previously, Windows PowerShell automatically prepends 'System.' to type names when you use New-Object. The same thing happens when using a bracketed type name, so you can specify [System.Environment] as [Environment].

The System.Environment class contains general information about the working environment for the current process, which is powershell.exe when working within Windows PowerShell.

If you try to view details of this class by typing [System.Environment] | Get-Member, the object type is reported as being System.RuntimeType , not System.Environment:

PS> [System.Environment] | Get-Member

   TypeName: System.RuntimeType

To view static members with Get-Member, specify the Static parameter:

PS> [System.Environment] | Get-Member -Static

   TypeName: System.Environment

Name                       MemberType Definition
----                       ---------- ----------
Equals                     Method     static System.Boolean Equals(Object ob...
Exit                       Method     static System.Void Exit(Int32 exitCode)
...
CommandLine                Property   static System.String CommandLine {get;}
CurrentDirectory           Property   static System.String CurrentDirectory ...
ExitCode                   Property   static System.Int32 ExitCode {get;set;}
HasShutdownStarted         Property   static System.Boolean HasShutdownStart...
MachineName                Property   static System.String MachineName {get;}
NewLine                    Property   static System.String NewLine {get;}
OSVersion                  Property   static System.OperatingSystem OSVersio...
ProcessorCount             Property   static System.Int32 ProcessorCount {get;}
StackTrace                 Property   static System.String StackTrace {get;}
SystemDirectory            Property   static System.String SystemDirectory {...
TickCount                  Property   static System.Int32 TickCount {get;}
UserDomainName             Property   static System.String UserDomainName {g...
UserInteractive            Property   static System.Boolean UserInteractive ...
UserName                   Property   static System.String UserName {get;}
Version                    Property   static System.Version Version {get;}
WorkingSet                 Property   static System.Int64 WorkingSet {get;}
TickCount                               ExitCode

We can now select properties to view from System.Environment.

Displaying Static Properties of System.Environment

The properties of System.Environment are also static, and must be specified in a different way than normal properties. We use :: to indicate to Windows PowerShell that we want to work with a static method or property. To see the command that was used to launch Windows PowerShell, we check the CommandLine property by typing:

PS> [System.Environment]::Commandline
"C:\Program Files\Windows PowerShell\v1.0\powershell.exe"

To check the operating system version, display the OSVersion property by typing:

PS> [System.Environment]::OSVersion

           Platform ServicePack         Version             VersionString
           -------- -----------         -------             -------------
            Win32NT Service Pack 2      5.1.2600.131072     Microsoft Window...

We can check whether the computer is in the process of shutting down by displaying the HasShutdownStarted property:

PS> [System.Environment]::HasShutdownStarted
False

Doing Math with System.Math

The System.Math static class is useful for performing some mathematical operations. The important members of System.Math are mostly methods, which we can display by using Get-Member.

Note:

System.Math has several methods with the same name, but they are distinguished by the type of their parameters.

Type the following command to list the methods of the System.Math class.

PS> [System.Math] | Get-Member -Static -MemberType Methods

   TypeName: System.Math

Name            MemberType Definition
----            ---------- ----------
Abs             Method     static System.Single Abs(Single value), static Sy...
Acos            Method     static System.Double Acos(Double d)
Asin            Method     static System.Double Asin(Double d)
Atan            Method     static System.Double Atan(Double d)
Atan2           Method     static System.Double Atan2(Double y, Double x)
BigMul          Method     static System.Int64 BigMul(Int32 a, Int32 b)
Ceiling         Method     static System.Double Ceiling(Double a), static Sy...
Cos             Method     static System.Double Cos(Double d)
Cosh            Method     static System.Double Cosh(Double value)
DivRem          Method     static System.Int32 DivRem(Int32 a, Int32 b, Int3...
Equals          Method     static System.Boolean Equals(Object objA, Object ...
Exp             Method     static System.Double Exp(Double d)
Floor           Method     static System.Double Floor(Double d), static Syst...
IEEERemainder   Method     static System.Double IEEERemainder(Double x, Doub...
Log             Method     static System.Double Log(Double d), static System...
Log10           Method     static System.Double Log10(Double d)
Max             Method     static System.SByte Max(SByte val1, SByte val2), ...
Min             Method     static System.SByte Min(SByte val1, SByte val2), ...
Pow             Method     static System.Double Pow(Double x, Double y)
ReferenceEquals Method     static System.Boolean ReferenceEquals(Object objA...
Round           Method     static System.Double Round(Double a), static Syst...
Sign            Method     static System.Int32 Sign(SByte value), static Sys...
Sin             Method     static System.Double Sin(Double a)
Sinh            Method     static System.Double Sinh(Double value)
Sqrt            Method     static System.Double Sqrt(Double d)
Tan             Method     static System.Double Tan(Double a)
Tanh            Method     static System.Double Tanh(Double value)
Truncate        Method     static System.Decimal Truncate(Decimal d), static...

This displays several mathematical methods. Here is a list of commands that demonstrate how some of the common methods work:

PS> [System.Math]::Sqrt(9)
3
PS> [System.Math]::Pow(2,3)
8
PS> [System.Math]::Floor(3.3)
3
PS> [System.Math]::Floor(-3.3)
-4
PS> [System.Math]::Ceiling(3.3)
4
PS> [System.Math]::Ceiling(-3.3)
-3
PS> [System.Math]::Max(2,7)
7
PS> [System.Math]::Min(2,7)
2
PS> [System.Math]::Truncate(9.3)
9
PS> [System.Math]::Truncate(-9.3)
-9


Removing Objects from the Pipeline (Where-Object)

In Windows PowerShell, you often generate and pass along more objects to a pipeline than you want. You can specify the properties of particular objects to display by using the Format cmdlets, but this does not help with the problem of removing entire objects from the display. You may want to filter objects before the end of a pipeline, so you can perform actions on only a subset of the initially-generated objects.

Windows PowerShell includes a Where-Object cmdlet that allows you to test each object in the pipeline and only pass it along the pipeline if it meets a particular test condition. Objects that do not pass the test are removed from the pipeline. You supply the test condition as the value of the Where-Object FilterScript parameter.

Performing Simple Tests with Where-Object

The value of FilterScript is a script block - one or more Windows PowerShell commands surrounded by braces {} - that evaluates to true or false. These script blocks can be very simple, but creating them requires knowing about another Windows PowerShell concept, comparison operators. A comparison operator compares the items that appear on each side of it. Comparison operators begin with a '-' character and are followed by a name. Basic comparison operators work on almost any kind of object. The more advanced comparison operators might only work on text or arrays.

Note:

By default, when working with text, Windows PowerShell comparison operators are case-insensitive.

Due to parsing considerations, symbols such as <,>, and = are not used as comparison operators. Instead, comparison operators are comprised of letters. The basic comparison operators are listed in the following table.

Comparison Operator | Meaning | Example (returns true)
-eq | is equal to | 1 -eq 1
-ne | Is not equal to | 1 -ne 2
-lt | Is less than | 1 -lt 2
-le | Is less than or equal to | 1 -le 2
-gt | Is greater than | 2 -gt 1
-ge | Is greater than or equal to | 2 -ge 1
-like | Is like (wildcard comparison for text) | "file.doc" -like "f*.do?"
-notlike | Is not like (wildcard comparison for text) | "file.doc" -notlike "p*.doc"
-contains | Contains | 1,2,3 -contains 1
-notcontains | Does not contain | 1,2,3 -notcontains 4

Where-Object script blocks use the special variable '$_' to refer to the current object in the pipeline. Here is an example of how it works. If you have a list of numbers, and only want to return the ones that are less than 3, you can use Where-Object to filter the numbers by typing:

PS> 1,2,3,4 | Where-Object -FilterScript {$_ -lt 3}
1
2

Filtering Based on Object Properties

Since $_ refers to the current pipeline object, we can access its properties for our tests.

As an example, we can look at the Win32_SystemDriver class in WMI. There might be hundreds of system drivers on a particular system, but you might only be interested in a particular set of the system drivers, such as those which are currently running. If you use Get-Member to view Win32_SystemDriver members (Get-WmiObject -Class Win32_SystemDriver | Get-Member -MemberType Property) you will see that the relevant property is State, and that it has a value of "Running" when the driver is running. You can filter the system drivers, selecting only the running ones by typing:

Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"}

This still produces a long list. You may want to filter to only select the drivers set to start automatically by testing the StartMode value as well:

PS> Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"} | Where-Object -FilterScript {$_.StartMode -eq "Auto"}

DisplayName : RAS Asynchronous Media Driver
Name        : AsyncMac
State       : Running
Status      : OK
Started     : True

DisplayName : Audio Stub Driver
Name        : audstub
State       : Running
Status      : OK
Started     : True

This gives us a lot of information we no longer need because we know that the drivers are running. In fact, the only information we probably need at this point are the name and the display name. The following command includes only those two properties, resulting in much simpler output:

PS> Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"} | Where-Object -FilterScript {$_.StartMode -eq "Manual"} | Format-Table -Property Name,DisplayName

Name                                    DisplayName
----                                    -----------
AsyncMac                                RAS Asynchronous Media Driver
Fdc                                     Floppy Disk Controller Driver
Flpydisk                                Floppy Disk Driver
Gpc                                     Generic Packet Classifier
IpNat                                   IP Network Address Translator
mouhid                                  Mouse HID Driver
MRxDAV                                  WebDav Client Redirector
mssmbios                                Microsoft System Management BIOS Driver

There are two Where-Object elements in the above command, but they can be expressed in a single Where-Object element by using the -and logical operator, like this:

Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript { ($_.State -eq "Running") -and ($_.StartMode -eq "Manual") } | Format-Table -Property Name,DisplayName

The standard logical operators are listed in the following table.

Logical Operator | Meaning | Example (returns true)
-and | Logical and; true if both sides are true | (1 -eq 1) -and (2 -eq 2)
-or | Logical or; true if either side is true | (1 -eq 1) -or (1 -eq 2)
-not | Logical not; reverses true and false | -not (1 -eq 2)
! | Logical not; reverses true and false | !(1 -eq 2)


Repeating a Task for Multiple Objects (ForEach-Object)

The ForEach-Object cmdlet uses script blocks and the $_ descriptor for the current pipeline object to let you run a command on each object in the pipeline. This can be used to perform some complicated tasks.

One situation where this can be useful is manipulating data to make it more useful. For example, the Win32_LogicalDisk class from WMI can be used to return free space information for each local disk. The data is returned in terms of bytes, however, which makes it difficult to read:

PS> Get-WmiObject -Class Win32_LogicalDisk

DeviceID     : C:
DriveType    : 3
ProviderName :
FreeSpace    : 50665070592
Size         : 203912880128
VolumeName   : Local Disk

We can convert the FreeSpace value to megabytes by dividing each value by 1024 twice; after the first division, the data is in kilobytes, and after the second division it is megabytes. You can do that in a ForEach-Object script block by typing:

Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process {($_.FreeSpace)/1024.0/1024.0}
48318.01171875

Unfortunately, the output is now data with no associated label. Because WMI properties such as this are read-only, you cannot directly convert FreeSpace. If you type this:

Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process {$_.FreeSpace = ($_.FreeSpace)/1024.0/1024.0}

You get an error message:

"FreeSpace" is a ReadOnly property.
At line:1 char:70
+ Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process {$_.F <<<< r
eeSpace = ($_.FreeSpace)/1024.0/1024.0}

You could reorganize the data by using some advanced techniques, but a simpler approach is to create a new object, by using Select-Object.


Selecting Parts of Objects (Select-Object)

You can use the Select-Object cmdlet to create new, custom Windows PowerShell objects that contain properties selected from the objects you use to create them. Type the following command to create a new object that includes only the Name and FreeSpace properties of the Win32_LogicalDisk WMI class:

PS> Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace

Name                                    FreeSpace
----                                    ---------
C:                                      50664845312

You cannot see the type of data after issuing that command, but if you pipe the result to Get-Member after the Select-Object, you can tell that you have a new type of object, a PSCustomObject:

PS> Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace| Get-Member

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       System.Boolean Equals(Object obj)
GetHashCode Method       System.Int32 GetHashCode()
GetType     Method       System.Type GetType()
ToString    Method       System.String ToString()
FreeSpace   NoteProperty  FreeSpace=...
Name        NoteProperty System.String Name=C:

Select-Object has many uses. One of them is replicating data that you can then modify. We can now handle the problem we ran across in the previous section. We can update the value of FreeSpace in our newly-created objects and the output will include the descriptive label:

Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace | ForEach-Object -Process {$_.FreeSpace = ($_.FreeSpace)/1024.0/1024.0; $_}
Name                                                                  FreeSpace
----                                                                  ---------
C:                                                                48317.7265625


Sorting Objects

We can organize displayed data to make it easier to scan by using the Sort-Object cmdlet. Sort-Object takes the name of one or more properties to sort on, and returns data sorted by the values of those properties.

Consider the problem of listing Win32_SystemDriver instances. If we want to sort by State and then by Name, we can do it by typing:

Get-WmiObject -Class Win32_SystemDriver | Sort-Object -Property State,Name | Format-Table -Property Name,State,Started,DisplayName -AutoSize -Wrap

Although this is a lengthy display, you can see items with the same state grouped together:

Name           State   Started DisplayName
----           -----   ------- -----------
ACPI           Running    True Microsoft ACPI Driver
AFD            Running    True AFD
AmdK7          Running    True AMD K7 Processor Driver
AsyncMac       Running    True RAS Asynchronous Media Driver
...
Abiosdsk       Stopped   False Abiosdsk
ACPIEC         Stopped   False ACPIEC
aec            Stopped   False Microsoft Kernel Acoustic Echo Canceller
...

You can also sort the objects in reverse order by specifying the Descending parameter. This reverses the sort order so that names are sorted in reverse alphabetical order and numbers are sorted by descending size.

PS> Get-WmiObject -Class Win32_SystemDriver | Sort-Object -Property State,Name -Descending | Format-Table -Property Name,State,Started,DisplayName -AutoSize -Wrap

Name           State   Started DisplayName
----           -----   ------- -----------
WS2IFSL        Stopped   False Windows Socket 2.0 Non-IFS Service Provider Supp
                               ort Environment
wceusbsh       Stopped   False Windows CE USB Serial Host Driver...
...
wdmaud         Running    True Microsoft WINMM WDM Audio Compatibility Driver
Wanarp         Running    True Remote Access IP ARP Driver
...


Using Variables to Store Objects

Windows PowerShell works with objects. Windows PowerShell lets you create variables - essentially named objects - to preserve output to use later. If you are used to working with variables in other shells, remember that Windows PowerShell variables are objects, not text.

Variables are always specified with the initial character $, and can include any alphanumeric characters or the underscore in their names.

Creating a Variable

You can create a variable by typing a valid variable name:

PS> $loc
PS>

This returns no result because $loc does not have a value. You can create a variable and assign it a value in the same step. Windows PowerShell only creates the variable if it does not exist; otherwise, it assigns the specified value to the existing variable. To store your current location in the variable $loc, type:

$loc = Get-Location

There is no output displayed when you type this command because the output is sent to $loc. In Windows PowerShell, displayed output is a side effect of the fact that data which is not otherwise directed always gets sent to the screen. Typing $loc will show your current location:

PS> $loc

Path
----
C:\temp

You can use Get-Member to display information about the contents of variables. Piping $loc to Get-Member will show you that it is a PathInfo object, just like the output from Get-Location:

PS> $loc | Get-Member -MemberType Property

   TypeName: System.Management.Automation.PathInfo

Name         MemberType Definition
----         ---------- ----------
Drive        Property   System.Management.Automation.PSDriveInfo Drive {get;}
Path         Property   System.String Path {get;}
Provider     Property   System.Management.Automation.ProviderInfo Provider {...
ProviderPath Property   System.String ProviderPath {get;}

Manipulating Variables

Windows PowerShell provides several commands to manipulate variables. You can see a complete listing in a readable form by typing:

Get-Command -Noun Variable | Format-Table -Property Name,Definition -AutoSize -Wrap

In addition to the variables you create in your current Windows PowerShell session, there are several system-defined variables. You can use the Remove-Variable cmdlet to clear out all of the variables which are not controlled by Windows PowerShell. Type the following command to clear all variables:

Remove-Variable -Name * -Force -ErrorAction SilentlyContinue

This will produce the confirmation prompt you see below.

Confirm
Are you sure you want to perform this action?
Performing operation "Remove Variable" on Target "Name: Error".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):A

If you then run the Get-Variable cmdlet, you will see the remaining Windows PowerShell variables. Since there is also a variable Windows PowerShell drive, you can also display all Windows PowerShell variables by typing:

Get-ChildItem variable:

Using Cmd.exe Variables

Although Windows PowerShell is not Cmd.exe, it runs in a command shell environment and can use the same variables available in any environment in Windows. These variables are exposed through a drive named env:. You can view these variables by typing:

Get-ChildItem env:

Although the standard variable cmdlets are not designed to work with env: variables, you can still use them by specifying the env: prefix. For example, to see the operating system root directory, you can use the command-shell %SystemRoot% variable from within Windows PowerShell by typing:

PS> $env:SystemRoot
C:\WINDOWS

You can also create and modify environment variables from within Windows PowerShell. Environment variables accessed from Windows PowerShell conform to the normal rules for environment variables elsewhere in Windows.


Using Windows PowerShell for Administration

The fundamental goal of Windows PowerShell is providing better, easier administrative control over systems, either interactively or from script. This chapter walks through solutions to many specific problems in administering Windows systems with Windows PowerShell. Although we have not talked about scripts or functions in the Windows PowerShell User's Guide, the solutions can be used from scripts or as functions later. We will show examples that include functions as part of the solution to solve problems.

Throughout the solution descriptions, you will see a mix of solutions using specific cmdlets, the general Get-WmiObject cmdlet, and even external tools that are part of the Windows and .NET Framework infrastructures. Use of external tools is part of the long-term design intent of Windows PowerShell. Even as the system grows, users will continually encounter situations in which the available toolsets do not do everything they need. Rather than foster dependency on cmdlet implementations alone, Windows PowerShell tries to support integrating solutions from every possible alternative scenario.


Managing Processes with Process Cmdlets

You can use the Process cmdlets in Windows PowerShell to manage local and remote processes in Windows PowerShell.

Getting Processes (Get-Process)

To get the processes running on the local computer, run a Get-Process with no parameters.

You can get particular processes by specifying their process names or process IDs. The following command gets the Idle process:

PS> Get-Process -id 0
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
      0       0        0         16     0               0 Idle

Although it is normal for cmdlets to return no data in some situations, when you specify a process by its ProcessId, Get-Process generates an error if it finds no matches, because the usual intent is to retrieve a known running process. If there is no process with that Id, it is likely that the Id is incorrect or that the process of interest has already exited:

PS> Get-Process -Id 99
Get-Process : No process with process ID 99 was found.
At line:1 char:12
+ Get-Process  <<<< -Id 99

You can use the Name parameter of the Get-Process cmdlet to specify a subset of processes based on the process name. The Name parameter can take multiple names in a comma-separated list and it supports the use of wildcards, so you can type name patterns.

For example, the following command gets process whose names begin with "ex."

PS> Get-Process -Name ex*
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    234       7     5572      12484   134     2.98   1684 EXCEL
    555      15    34500      12384   134   105.25    728 explorer

Because the .NET System.Diagnostics.Process class is the foundation for Windows PowerShell processes, it follows some of the conventions used by System.Diagnostics.Process. One of those conventions is that the process name for an executable never includes the ".exe" at the end of the executable name.

Get-Process also accepts multiple values for the Name parameter.

PS> Get-Process -Name exp*,power*
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    540      15    35172      48148   141    88.44    408 explorer
    605       9    30668      29800   155     7.11   3052 powershell

You can use the ComputerName parameter of Get-Process to get processes on remote computers. For example, the following command gets the PowerShell processes on the local computer (represented by "localhost") and on two remote computers.

PS> Get-Process -Name PowerShell -ComputerName localhost, Server01, Server02
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    258       8    29772      38636   130            3700 powershell
    398      24    75988      76800   572            5816 powershell
    605       9    30668      29800   155     7.11   3052 powershell

The computer names are not evident in this display, but they are stored in the MachineName property of the process objects that Get-Process returns. The following command uses the Format-Table cmdlet to display the process ID, ProcessName and MachineName (ComputerName) properties of the process objects.

PS> Get-Process -Name PowerShell -ComputerName localhost, Server01, Server01 | Format-Table -Property ID, ProcessName, MachineName
  Id ProcessName MachineName
  -- ----------- -----------
3700 powershell  Server01
3052 powershell  Server02
5816 powershell  localhost

This more complex command adds the MachineName property to the standard Get-Process display. The backtick (`)(ASCII 96) is the Windows PowerShell continuation character.

get-process powershell -computername localhost, Server01, Server02 | format-table -property Handles, `
                    @{Label="NPM(K)";Expression={[int]($_.NPM/1024)}}, `
                    @{Label="PM(K)";Expression={[int]($_.PM/1024)}}, `
                    @{Label="WS(K)";Expression={[int]($_.WS/1024)}}, `
                    @{Label="VM(M)";Expression={[int]($_.VM/1MB)}}, `
                    @{Label="CPU(s)";Expression={if ($_.CPU -ne $()`
                    {$_.CPU.ToString("N")}}}, `
                    Id, ProcessName, MachineName -auto

Handles  NPM(K)  PM(K) WS(K) VM(M) CPU(s)  Id ProcessName  MachineName
-------  ------  ----- ----- ----- ------  -- -----------  -----------
    258       8  29772 38636   130         3700 powershell Server01
    398      24  75988 76800   572         5816 powershell localhost
    605       9  30668 29800   155 7.11    3052 powershell Server02

Stopping Processes (Stop-Process)

Windows PowerShell gives you flexibility for listing processes, but what about stopping a process?

The Stop-Process cmdlet takes a Name or Id to specify a process you want to stop. Your ability to stop processes depends on your permissions. Some processes cannot be stopped. For example, if you try to stop the idle process, you get an error:

PS> Stop-Process -Name Idle
Stop-Process : Process 'Idle (0)' cannot be stopped due to the following error:
 Access is denied
At line:1 char:13
+ Stop-Process  <<<< -Name Idle

You can also force prompting with the Confirm parameter. This parameter is particularly useful if you use a wildcard when specifying the process name, because you may accidentally match some processes you do not want to stop:

PS> Stop-Process -Name t*,e* -Confirm
Confirm
Are you sure you want to perform this action?
Performing operation "Stop-Process" on Target "explorer (408)".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):n
Confirm
Are you sure you want to perform this action?
Performing operation "Stop-Process" on Target "taskmgr (4072)".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):n

Complex process manipulation is possible by using some of the object filtering cmdlets. Because a Process object has a Responding property that is true when it is no longer responding, you can stop all nonresponsive applications with the following command:

Get-Process | Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process

You can use the same approach in other situations. For example, suppose a secondary notification area application automatically runs when users start another application. You may find that this does not work correctly in Terminal Services sessions, but you still want to keep it in sessions that run on the physical computer console. Sessions connected to the physical computer desktop always have a session ID of 0, so you can stop all instances of the process that are in other sessions by using Where-Object and the process, SessionId:

Get-Process -Name BadApp | Where-Object -FilterScript {$_.SessionId -neq 0} | Stop-Process

The Stop-Process cmdlet does not have a ComputerName parameter. Therefore, to run a stop process command on a remote computer, you need to use the Invoke-Command cmdlet. For example, to stop the PowerShell process on the Server01 remote computer, type:

Invoke-Command -ComputerName Server01 {Stop-Process Powershell}

Stopping All Other Windows PowerShell Sessions

It may occasionally be useful to be able to stop all running Windows PowerShell sessions other than the current session. If a session is using too many resources or is inaccessible (it may be running remotely or in another desktop session), you may not be able to directly stop it. If you try to stop all running sessions, however, the current session may be terminated instead.

Each Windows PowerShell session has an environment variable PID that contains the Id of the Windows PowerShell process. You can check the $PID against the Id of each session and terminate only Windows PowerShell sessions that have a different Id. The following pipeline command does this and returns the list of terminated sessions (because of the use of the PassThru parameter):

PS> Get-Process -Name powershell | Where-Object -FilterScript {$_.Id -ne $PID} | Stop-Process -
PassThru
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    334       9    23348      29136   143     1.03    388 powershell
    304       9    23152      29040   143     1.03    632 powershell
    302       9    20916      26804   143     1.03   1116 powershell
    335       9    25656      31412   143     1.09   3452 powershell
    303       9    23156      29044   143     1.05   3608 powershell
    287       9    21044      26928   143     1.02   3672 powershell

Starting, Debugging, and Waiting for Processes

Windows PowerShell also comes with cmdlets to start (or restart), debug a process, and wait for a process to complete before running a command. For information about these cmdlets, see the cmdlet help topic for each cmdlet.

See Also

  • Get-Process
  • Stop-Process
  • Start-Process
  • Wait-Process
  • Debug-Process
  • Invoke-Command


Managing Services

There are eight core Service cmdlets, designed for a wide range of service tasks . We will look only at listing and changing running state for services, but you can get a list Service cmdlets by using Get-Help *-Service, and you can find information about each Service cmdlet by using Get-Help <Cmdlet-Name>, such as Get-Help New-Service.

Getting Services

You can get the services on a local or remote computer by using the Get-Service cmdlet. As with Get-Process, using the Get-Service command without parameters returns all services. You can filter by name, even using an asterisk as a wildcard:

PS> Get-Service -Name se*
Status   Name               DisplayName
------   ----               -----------
Running  seclogon           Secondary Logon
Running  SENS               System Event Notification
Stopped  ServiceLayer       ServiceLayer

Because it is not always obvious what the real name for the service is, you may find you need to find services by display name. You can do this by specific name, using wildcards, or using a list of display names:

PS> Get-Service -DisplayName se*
Status   Name               DisplayName
------   ----               -----------
Running  lanmanserver       Server
Running  SamSs              Security Accounts Manager
Running  seclogon           Secondary Logon
Stopped  ServiceLayer       ServiceLayer
Running  wscsvc             Security Center
PS> Get-Service -DisplayName ServiceLayer,Server
Status   Name               DisplayName
------   ----               -----------
Running  lanmanserver       Server
Stopped  ServiceLayer       ServiceLayer

You can use the ComputerName parameter of the Get-Service cmdlet to get the services on remote computers. The ComputerName parameter accepts multiple values and wildcard characters, so you can get the services on multiple computers with a single command. For example, the following command gets the services on the Server01 remote computer.

Get-Service -ComputerName Server01

Getting Required and Dependent Services

The Get-Service cmdlet has two parameters that are very useful in service administration. The DependentServices parameter gets services that depend on the service. The RequiredServices parameter gets services upon which this service depends.

These parameters just display the values of the DependentServices and ServicesDependedOn (alias=RequiredServices) properties of the System.ServiceProcess.ServiceController object that Get-Service returns, but they simplify commands and make getting this information much simpler.

The following command gets the services that the LanmanWorkstation service requires.

PS> Get-Service -Name LanmanWorkstation -RequiredServices
Status   Name               DisplayName
------   ----               -----------
Running  MRxSmb20           SMB 2.0 MiniRedirector
Running  bowser             Bowser
Running  MRxSmb10           SMB 1.x MiniRedirector
Running  NSI                Network Store Interface Service

The following command gets the services that require the LanmanWorkstation service.

PS> Get-Service -Name LanmanWorkstation -DependentServices
Status   Name               DisplayName
------   ----               -----------
Running  SessionEnv         Terminal Services Configuration
Running  Netlogon           Netlogon
Stopped  Browser            Computer Browser
Running  BITS               Background Intelligent Transfer Ser...

You can even get all services that have dependencies. The following command does just that, and then it uses the Format-Table cmdlet to display the Status, Name, RequiredServices and DependentServices properties of the services on the computer.

Get-Service -Name * | where {$_.RequiredServices -or $_.DependentServices} | Format-Table -Property Status, Name, RequiredServices, DependentServices -auto

Stopping, Starting, Suspending, and Restarting Services

The Service cmdlets all have the same general form. Services can be specified by common name or display name, and take lists and wildcards as values. To stop the print spooler, use:

Stop-Service -Name spooler

To start the print spooler after it is stopped, use:

Start-Service -Name spooler

To suspend the print spooler, use:

Suspend-Service -Name spooler

The Restart-Service cmdlet works in the same manner as the other Service cmdlets, but we will show some more complex examples for it. In the simplest use, you specify the name of the service:

PS> Restart-Service -Name spooler
WARNING: Waiting for service 'Print Spooler (Spooler)' to finish starting...
WARNING: Waiting for service 'Print Spooler (Spooler)' to finish starting...
PS>

You will notice that you get a repeated warning message about the Print Spooler starting up. When you perform a service operation that takes some time, Windows PowerShell will notify you that it is still attempting to perform the task.

If you want to restart multiple services, you can get a list of services, filter them, and then perform the restart:

PS> Get-Service | Where-Object -FilterScript {$_.CanStop} | Restart-Service
WARNING: Waiting for service 'Computer Browser (Browser)' to finish stopping...
WARNING: Waiting for service 'Computer Browser (Browser)' to finish stopping...
Restart-Service : Cannot stop service 'Logical Disk Manager (dmserver)' because
 it has dependent services. It can only be stopped if the Force flag is set.
At line:1 char:57
+ Get-Service | Where-Object -FilterScript {$_.CanStop} | Restart-Service <<<<
WARNING: Waiting for service 'Print Spooler (Spooler)' to finish starting...
WARNING: Waiting for service 'Print Spooler (Spooler)' to finish starting...

These Service cmdlets do not have a ComputerName parameter, but you can run them on a remote computer by using the Invoke-Command cmdlet. For example, the following command restarts the Spooler service on the Server01 remote computer.

Invoke-Command -ComputerName Server01 {Restart-Service Spooler}

Setting Service Properties

The Set-Service cmdlet changes the properties of a service on a local or remote computer. Because the service status is a property, you can use this cmdlet to start, stop, and suspend a service. The Set-Service cmdlet also has a StartupType parameter that lets you change the service startup type.

To use Set-Service on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administrator" option.

For more information, see Set-Service

See Also

  • Get-Service
  • Set-Service
  • Restart-Service
  • Suspend-Service


Collecting Information About Computers

Get-WmiObject is the most important cmdlet for general system management tasks. All critical subsystem settings are exposed through WMI. Furthermore, WMI treats data as objects that are in collections of one or more items. Because Windows PowerShell also works with objects and has a pipeline that allows you to treat single or multiple objects in the same way, generic WMI access allows you to perform some advanced tasks with very little work.

The following examples demonstrate how to collect specific information by using Get-WmiObject against an arbitrary computer. We specify the ComputerName parameter with the dot value (.), which represents the local computer. You can specify a name or IP address associated with any computer you can reach through WMI. To retrieve information about the local computer, you could omit the -ComputerName.

Listing Desktop Settings

We'll begin with a command that collects information about the desktops on the local computer.

Get-WmiObject -Class Win32_Desktop -ComputerName .

This returns information for all desktops, whether they are in use or not.

Note:

Information returned by some WMI classes can be very detailed, and often include metadata about the WMI class. Because most of these metadata properties have names that begin with a double-underscore, you can filter the properties using Select-Object. Specify only properties that begin with alphabetic characters by using [a-z]* as the Property value. For example:

Get-WmiObject -Class Win32_Desktop -ComputerName . | Select-Object -Property [a-z]*

To filter out the metadata, use a pipeline operator (|) to send the results of the Get-WmiObject command to Select-Object -Property [a-z]*.

Listing BIOS Information

The WMI Win32_BIOS class returns fairly compact and complete information about the system BIOS on the local computer:

Get-WmiObject -Class Win32_BIOS -ComputerName .

Listing Processor Information

You can retrieve general processor information by using WMI's Win32_Processor class, although you will likely want to filter the information:

Get-WmiObject -Class Win32_Processor -ComputerName . | Select-Object -Property [a-z]*

For a generic description string of the processor family, you can just return the Win32_ComputerSystem SystemType property:

PS> Get-WmiObject -Class Win32_ComputerSystem -ComputerName . | Select-Object -Property SystemType
SystemType
----------
X86-based PC

Listing Computer Manufacturer and Model

Computer model information is also available from Win32_ComputerSystem. The standard displayed output will not need any filtering to provide OEM data:

PS> Get-WmiObject -Class Win32_ComputerSystem
Domain              : WORKGROUP
Manufacturer        : Compaq Presario 06
Model               : DA243A-ABA 6415cl NA910
Name                : MyPC
PrimaryOwnerName    : Jane Doe
TotalPhysicalMemory : 804765696

Your output from commands such as this, which return information directly from some hardware, is only as good as the data you have. Some information is not correctly configured by hardware manufacturers and may therefore be unavailable.

Listing Installed Hotfixes

You can list all installed hotfixes by using Win32_QuickFixEngineering:

Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName .

This class returns a list of hotfixes that looks like this:

Description         : Update for Windows XP (KB910437)
FixComments         : Update
HotFixID            : KB910437
Install Date        :
InstalledBy         : Administrator
InstalledOn         : 12/16/2005
Name                :
ServicePackInEffect : SP3
Status              :

For more succinct output, you may want to exclude some properties. Although you can use the Get-WmiObject Property parameter to choose only the HotFixID, doing so will actually return more information, because all the metadata is displayed by default:

PS> Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName . -Property HotFixId
HotFixID         : KB910437
__GENUS          : 2
__CLASS          : Win32_QuickFixEngineering
__SUPERCLASS     :
__DYNASTY        :
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :

The additional data is returned, because the Property parameter in Get-WmiObject restricts the properties returned from WMI class instances, not the object returned to Windows PowerShell. To reduce the output, use Select-Object:

PS> Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName . -Property Hot
FixId | Select-Object -Property HotFixId
HotFixId
--------
KB910437

Listing Operating System Version Information

The Win32_OperatingSystem class properties include version and service pack information. You can explicitly select only these properties to get a version information summary from Win32_OperatingSystem:

Get-WmiObject -Class Win32_OperatingSystem -ComputerName . | Select-Object -Property BuildNumber,BuildType,OSType,ServicePackMajorVersion,ServicePackMinorVersion

You can also use wildcards with the Select-Object Property parameter. Because all the properties beginning with either Build or ServicePack are important to use here, we can shorten this to the following form:

PS> Get-WmiObject -Class Win32_OperatingSystem -ComputerName . | Select-Object -Property Build*,OSType,ServicePack*

BuildNumber             : 2600
BuildType               : Uniprocessor Free
OSType                  : 18
ServicePackMajorVersion : 2
ServicePackMinorVersion : 0

Listing Local Users and Owner

Local general user information—number of licensed users, current number of users, and owner name—can be found with a selection of Win32_OperatingSystem properties. You can explicitly select the properties to display like this:

Get-WmiObject -Class Win32_OperatingSystem -ComputerName . | Select-Object -Property NumberOfLicensedUsers,NumberOfUsers,RegisteredUser

A more succinct version using wildcards is:

Get-WmiObject -Class Win32_OperatingSystem -ComputerName . | Select-Object -Property *user*

Getting Available Disk Space

To see the disk space and free space for local drives, you can use the WMI Win32_LogicalDisk class. You need to see only instances with a DriveType of 3—the value WMI uses for fixed hard disks.

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .

DeviceID     : C:
DriveType    : 3
ProviderName :
FreeSpace    : 65541357568
Size         : 203912880128
VolumeName   : Local Disk

DeviceID     : Q:
DriveType    : 3
ProviderName :
FreeSpace    : 44298250240
Size         : 122934034432
VolumeName   : New Volume

PS> Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName . | Measure-Object -Property FreeSpace,Size -Sum

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName . | Measure-Object -Property FreeSpace,Size -Sum | Select-Object -Property Property,Sum

Getting Logon Session Information

You can get general information about logon sessions associated with users through the WMI Win32_LogonSession class:

Get-WmiObject -Class Win32_LogonSession -ComputerName .

Getting the User Logged on to a Computer

You can display the user logged on to a particular computer system using Win32_ComputerSystem. This command returns only the user logged on to the system desktop:

Get-WmiObject -Class Win32_ComputerSystem -Property UserName -ComputerName .

Getting Local Time from a Computer

You can retrieve the current local time on a specific computer by using the WMI Win32_LocalTime class. Because this class by default displays all metadata, you may want to filter it using Select-Object:

PS> Get-WmiObject -Class Win32_LocalTime -ComputerName . | Select-Object -Property [a-z]*

Day          : 15
DayOfWeek    : 4
Hour         : 12
Milliseconds :
Minute       : 11
Month        : 6
Quarter      : 2
Second       : 52
WeekInMonth  : 3
Year         : 2006

Displaying Service Status

To view the status of all services on a specific computer, you can locally use the Get-Service cmdlet as mentioned earlier. For remote systems, you can use the WMI Win32_Service class. If you also use Select-Object to filter the results to Status, Name, and DisplayName, the output format will be almost identical to that from Get-Service:

Get-WmiObject -Class Win32_Service -ComputerName . | Select-Object -Property Status,Name,DisplayName

To allow the complete display of names for the occasional services with extremely long names, you may want to use Format-Table with the AutoSize and Wrap parameters, to optimize column width and allow long names to wrap instead of being truncated:

Get-WmiObject -Class Win32_Service -ComputerName . | Format-Table -Property Status,Name,DisplayName -AutoSize -Wrap


Working with Software Installations

Applications that are designed to use Windows Installer can be accessed through WMI's Win32_Product class, but not all applications in use today use the Windows Installer. Because the Windows Installer provides the widest range of standard techniques for working with installable applications, we will focus primarily on those applications. Applications that use alternate setup routines will generally not be managed by the Windows Installer. Specific techniques for working with those applications will depend on the installer software and decisions made by the application developer.

Note:

Applications that are installed by copying the application files to the computer usually cannot be managed by using techniques discussed here. You can manage these applications as files and folders by using the techniques discussed in the "Working With Files and Folders" section.

Listing Windows Installer Applications

To list the applications installed with the Windows Installer on a local or remote system, use the following simple WMI query:

PS> Get-WmiObject -Class Win32_Product -ComputerName .
IdentifyingNumber : {7131646D-CD3C-40F4-97B9-CD9E4E6262EF}
Name              : Microsoft .NET Framework 2.0
Vendor            : Microsoft Corporation
Version           : 2.0.50727
Caption           : Microsoft .NET Framework 2.0

To display all of the properties of the Win32_Product object to the display, use the Properties parameter of the formatting cmdlets, such as the Format-List cmdlet, with a value of * (all).

PS> Get-WmiObject -Class Win32_Product -ComputerName . | Where-Object -FilterScript {$_.Name -eq "Microsoft .NET Framework 2.0"} | Format-List -Property *
Name              : Microsoft .NET Framework 2.0
Version           : 2.0.50727
InstallState      : 5
Caption           : Microsoft .NET Framework 2.0
Description       : Microsoft .NET Framework 2.0
IdentifyingNumber : {7131646D-CD3C-40F4-97B9-CD9E4E6262EF}
InstallDate       : 20060506
InstallDate2      : 20060506000000.000000-000
InstallLocation   :
PackageCache      : C:\WINDOWS\Installer\619ab2.msi
SKUNumber         :
Vendor            : Microsoft Corporation

Or, you could use the Get-WmiObject Filter parameter to select only Microsoft .NET Framework 2.0. Because the filter used in this command is a WMI filter, it uses WMI Query Language (WQL) syntax, not Windows PowerShell syntax. Instead,:

Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='Microsoft .NET Framework 2.0'"| Format-List -Property *

Note that WQL queries frequently use characters, such as spaces or equal signs, that have a special meaning in Windows PowerShell. For this reason, it is prudent to always enclose the value of the Filter parameter in quotation marks. You can also use the Windows PowerShell escape character, a backtick (`), although it may not improve readability. The following command is equivalent to the previous command and returns the same results, but uses the backtick to escape special characters, instead of quoting the entire filter string.

Get-WmiObject -Class Win32_Product -ComputerName . -Filter Name`=`'Microsoft` .NET` Framework` 2.0`' | Format-List -Property *

To list only the properties that interest you, use the Property parameter of the formatting cmdlets to list the desired properties.

Get-WmiObject -Class Win32_Product -ComputerName . | Format-List -Property Name,InstallDate,InstallLocation,PackageCache,Vendor,Version,IdentifyingNumber
...
Name              : HighMAT Extension to Microsoft Windows XP CD Writing Wizard
InstallDate       : 20051022
InstallLocation   : C:\Program Files\HighMAT CD Writing Wizard\
PackageCache      : C:\WINDOWS\Installer\113b54.msi
Vendor            : Microsoft Corporation
Version           : 1.1.1905.1
IdentifyingNumber : {FCE65C4E-B0E8-4FBD-AD16-EDCBE6CD591F}
...

Finally, to find only the names of installed applications, a simple Format-Wide statement simplifies the output:

Get-WmiObject -Class Win32_Product -ComputerName .  | Format-Wide -Column 1

Although we now have several ways to look at applications that used the Windows Installer for installation, we have not considered other applications. Because most standard applications register their uninstaller with Windows, we can work with those locally by finding them in the Windows registry.

Listing All Uninstallable Applications

Although there is no guaranteed way to find every application on a system, it is possible to find all programs with listings displayed in the Add or Remove Programs dialog box. Add or Remove Programs finds these applications in the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall.

We can also examine this key to find applications. To make it easier to view the Uninstall key, we can map a Windows PowerShell drive to this registry location:

PS>

Name       Provider      Root                                   CurrentLocation
----       --------      ----                                   ---------------
Uninstall  Registry      HKEY_LOCAL_MACHINE\SOFTWARE\Micr...
Note:

The HKLM: drive is mapped to the root of HKEY_LOCAL_MACHINE, so we used that drive in the path to the Uninstall key. Instead of HKLM: we could have specified the registry path by using either HKLM or HKEY_LOCAL_MACHINE. The advantage of using an existing registry drive is that we can use tab-completion to fill in the keys names, so we do not need to type them.

We now have a drive named "Uninstall" that can be used to quickly and conveniently look for application installations. We can find the number of installed applications by counting the number of registry keys in the Uninstall: Windows PowerShell drive:

PS> (Get-ChildItem -Path Uninstall:).Count
459

We can search this list of applications further by using a variety of techniques, beginning with Get-ChildItem. To get a list of applications and save them in the $UninstallableApplications variable, use the following command:

$UninstallableApplications = Get-ChildItem -Path Uninstall:
Note:

We are using a lengthy variable name here for clarity. In actual use, there is no reason to use long names. Although you can use tab-completion for variable names, you can also use 1–2 character names for speed. Longer, descriptive names are most useful when you are developing code for reuse.

To display the values of the registry entries in the registry keys under Uninstall, use the GetValue method of the registry keys. The value of the method is the name of the registry entry.

For example, to find the display names of applications in the Uninstall key, use the following command:

PS> Get-ChildItem -Path Uninstall: | ForEach-Object -Process { $_.GetValue("DisplayName") }

There is no guarantee that these values are unique. In the following example, two installed items appear as "Windows Media Encoder 9 Series":

PS> Get-ChildItem -Path Uninstall: | Where-Object -FilterScript { $_.GetValue("DisplayName") -eq "Windows Media Encoder 9 Series"}

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Micros
oft\Windows\CurrentVersion\Uninstall

SKC  VC Name                           Property
---  -- ----                           --------
  0   3 Windows Media Encoder 9        {DisplayName, DisplayIcon, UninstallS...
  0  24 {E38C00D0-A68B-4318-A8A6-F7... {AuthorizedCDFPrefix, Comments, Conta...

Installing Applications

You can use the Win32_Product class to install Windows Installer packages, remotely or locally. When installing remotely, use a Universal Naming Convention (UNC) network path to specify the path to the .msi package, because the WMI subsystem does not understand Windows PowerShell paths. For example, to install the NewPackage.msi package located in the network share \\AppServ\dsp on the remote computer PC01, type the following command at the Windows PowerShell prompt:

(Get-WMIObject -ComputerName PC01 -List | Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).Install(\\AppSrv\dsp\NewPackage.msi)

Applications that do not use Windows Installer technology may have application-specific methods available for automated deployment. To determine whether there is a method for deployment automation, check the documentation for the application or consult the application vendor's support system. In some cases, even if the application vendor did not specifically design the application for installation automation, the installer software manufacturer may have some techniques for automation.

Removing Applications

Removing a Windows Installer package by using Windows PowerShell works in approximately the same way as installing a package. Here is an example that selects the package to uninstall based on its name; in some cases it may be easier to filter with the IdentifyingNumber:

(Get-WmiObject -Class Win32_Product -Filter "Name='ILMerge'" -ComputerName . ).Uninstall()

Removing other applications is not quite so simple, even when done locally. We can find the command line uninstallation strings for these applications by extracting the UninstallString property. This method works for Windows Installer applications and for older programs appearing under the Uninstall key:

Get-ChildItem -Path Uninstall: | ForEach-Object -Process { $_.GetValue("UninstallString") }

You can filter the output by the display name, if you like:

Get-ChildItem -Path Uninstall: | Where-Object -FilterScript { $_.GetValue("DisplayName") -like "Win*"} | ForEach-Object -Process { $_.GetValue("UninstallString") }

However, these strings may not be directly usable from the Windows PowerShell prompt without some modification.

Upgrading Windows Installer Applications

To upgrade an application, you need to know the name of the application and the path to the application upgrade package. With that information, you can upgrade an application with a single Windows PowerShell command:

(Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='OldAppName'").Upgrade(\\AppSrv\dsp\OldAppUpgrade.msi)


Changing Computer State

To reset a computer in Windows PowerShell, use either a standard command-line tool or a WMI class. Although you are using Windows PowerShell only to run the tool, learning how to change a computer's power state in Windows PowerShell illustrates some of the important details about working with external tools in Windows PowerShell.

Locking a Computer

The only way to lock a computer directly with the standard available tools is to call the LockWorkstation() function in user32.dll:

rundll32.exe user32.dll,LockWorkStation

This command immediately locks the workstation. It uses rundll32.exe, which runs Windows DLLs (and saves their libraries for repeated use) to run user32.dll, a library of Windows management functions.

When you lock a workstation while Fast User Switching is enabled, such as on Windows XP, the computer displays the user logon screen rather than starting the current user's screensaver.

To shut down particular sessions on a Terminal Server, use the tsshutdn.exe command line tool.

Logging Off the Current Session

You can use several different techniques to log off of a session on the local system. The simplest way is to use the Remote Desktop/Terminal Services command-line tool, logoff.exe (For details, at the Windows PowerShell prompt, type logoff /?). To log off the current active session, type logoff with no arguments.

You can also use the shutdown.exe tool with its logoff option:

shutdown.exe -l

A third option is to use WMI. The Win32_OperatingSystem class has a Win32Shutdown method. Invoking the method with the 0 flag initiates logoff:

(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(0)

For more information, and to find other features of the Win32Shutdown method, see "Win32Shutdown Method of the Win32_OperatingSystem Class" in MSDN.

Shutting Down or Restarting a Computer

Shutting down and restarting computers are generally the same types of task. Tools that shut down a computer will generally restart it as well—and vice versa. There are two straightforward options for restarting a computer from Windows PowerShell. Use either Tsshutdn.exe or Shutdown.exe with appropriate arguments. You can get detailed usage information from tsshutdn.exe /? or shutdown.exe /?.

You can also perform shutdown and restart operations by using Win32_OperatingSystem directly from Windows PowerShell as well.

To shut down the computer, use the Win32Shutdown method with the 1 flag.

(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(1)

To restart the operating system, use the Win32Shutdown method with the 2 flag.

(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(2)


Working with Printers

You can use Windows PowerShell to manage printers by using WMI and the WScript.Network COM object from WSH. We will use a mix of both tools to demonstrate specific tasks.

Listing Printer Connections

The simplest way to list the printers installed on a computer is to use the WMI Win32_Printer class:

Get-WmiObject -Class Win32_Printer -ComputerName

You can also list the printers by using the WScript.Network COM object that is typically used in WSH scripts:

(New-Object -ComObject WScript.Network).EnumPrinterConnections()

Because this command returns a simple string collection of port names and printer device names without any distinguishing labels, it is not easy to interpret.

Adding a Network Printer

To add a new network printer, use WScript.Network:

(New-Object -ComObject WScript.Network).AddWindowsPrinterConnection("\\Printserver01\Xerox5")

Setting a Default Printer

To use WMI to set the default printer, find the printer in the Win32_Printer collection and then invoke the SetDefaultPrinter method:

(Get-WmiObject -ComputerName . -Class Win32_Printer -Filter "Name='HP LaserJet 5Si'").SetDefaultPrinter()

WScript.Network is a little simpler to use, because it has a SetDefaultPrinter method that takes only the printer name as an argument:

(New-Object -ComObject WScript.Network).SetDefaultPrinter('HP LaserJet 5Si')

Removing a Printer Connection

To remove a printer connection, use the WScript.Network RemovePrinterConnection method:

(New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Printserver01\Xerox5")


Performing Networking Tasks

Because TCP/IP is the most commonly used network protocol, most low-level network protocol administration tasks involve TCP/IP. In this section, we use Windows PowerShell and WMI to do these tasks.

Listing IP Addresses for a Computer

To get all IP addresses in use on the local computer, use the following command:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Format-Table -Property IPAddress

The output of this command differs from most property lists, because values are enclosed in braces:

IPAddress

---------

{192.168.1.80}

{192.168.148.1}

{192.168.171.1}

{0.0.0.0}

To understand why the braces appear, use the Get-Member cmdlet to examine the IPAddress property:

PS> Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Get-Member -Name IPAddress

TypeName: System.Management.ManagementObject#root\cimv2\Win32_NetworkAdapter

Configuration

Name MemberType Definition

---- ---------- ----------

IPAddress Property System.String[] IPAddress {get;}

The IPAddress property for each network adapter is actually an array. The braces in the definition indicate that IPAddress is not a System.String value, but an array of System.String values.

Listing IP Configuration Data

To display detailed IP configuration data for each network adapter, use the following command:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .

The default display for the network adapter configuration object is a very reduced set of the available information. For in-depth inspection and troubleshooting, use Select-Object or a formatting cmdlet, such as Format-List, to specify the properties to be displayed.

If you are not interested in IPX or WINS properties—probably the case in a modern TCP/IP network—you can use the ExcludeProperty parameter of Select-Object to hide properties with names that begin with "WINS" or "IPX:"

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*

This command returns detailed information about DHCP, DNS, routing, and other minor IP configuration properties.

Pinging Computers

You can perform a simple ping against a computer using by Win32_PingStatus. The following command performs the ping, but returns lengthy output:

Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .

A more useful form for summary information a display of the Address, ResponseTime, and StatusCode properties, as generated by the following command. The Autosize parameter of Format-Table resizes the table columns so that they display properly in Windows PowerShell.

PS> Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName . | Format-Table -Property Address,ResponseTime,StatusCode -Autosize

Address   ResponseTime StatusCode
-------   ------------ ----------
127.0.0.1            0          0
A status code of 0 indicates a successful ping.

You can use an array to ping multiple computers with a single command. Because there is more than one address, use the ForEach-Object to ping each address separately:

"127.0.0.1","localhost","research.microsoft.com" | ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus -Filter ("Address='" + $_ + "'") -ComputerName .} | Select-Object -Property Address,ResponseTime,StatusCode

You can use the same command format to ping all of the computers on a subnet, such as a private network that uses network number 192.168.1.0 and a standard Class C subnet mask (255.255.255.0)., Only addresses in the range of 192.168.1.1 through 192.168.1.254 are legitimate local addresses (0 is always reserved for the network number and 255 is a subnet broadcast address).

To represent an array of the numbers from 1 through 254 in Windows PowerShell, use the statement 1..254. A complete subnet ping can be performed by generating the array and then adding the values onto a partial address in the ping statement:

1..254| ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus -Filter ("Address='192.168.1." + $_ + "'") -ComputerName .} | Select-Object -Property Address,ResponseTime,StatusCode

Note that this technique for generating a range of addresses can be used elsewhere as well. You can generate a complete set of addresses in this way:

$ips = 1..254 | ForEach-Object -Process {"192.168.1." + $_}

Retrieving Network Adapter Properties

Earlier in this user's guide, we mentioned that you could retrieve general configuration properties by using Win32_NetworkAdapterConfiguration. Although not strictly TCP/IP information, network adapter information such as MAC addresses and adapter types can be useful for understanding what is going on with a computer. To get a summary of this information, use the following command:

Get-WmiObject -Class Win32_NetworkAdapter -ComputerName .

Assigning the DNS Domain for a Network Adapter

To assign the DNS domain for automatic name resolution, use the Win32_NetworkAdapterConfiguration SetDNSDomain method. Because you assign the DNS domain for each network adapter configuration independently, you need to use a ForEach-Object statement to assign the domain to each adapter:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName . | ForEach-Object -Process { $_. SetDNSDomain("fabrikam.com") }

The filtering statement "IPEnabled=true" is necessary, because even on a network that uses only TCP/IP, several of the network adapter configurations on a computer are not true TCP/IP adapters; they are general software elements supporting RAS, PPTP, QoS, and other services for all adapters and thus do not have an address of their own.

You can filter the command by using the Where-Object cmdlet, instead of using the Get-WmiObject filter.

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName . | Where-Object -FilterScript {$_.IPEnabled} | ForEach-Object -Process {$_.SetDNSDomain("fabrikam.com")}

Performing DHCP Configuration Tasks

Modifying DHCP details involves working with a set of network adapters, just as the DNS configuration does. There are several distinct actions you can perform by using WMI, and we will step through a few of the common ones.

Determining DHCP-Enabled Adapters

To find the DHCP-enabled adapters on a computer, use the following command:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "DHCPEnabled=true" -ComputerName .

To exclude adapters with IP configuration problems, you can retrieve only IP-enabled adapters:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true and DHCPEnabled=true" -ComputerName .

Retrieving DHCP Properties

Because DHCP-related properties for an adapter generally begin with "DHCP," you can use the Property parameter of Format-Table to display only those properties:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "DHCPEnabled=true" -ComputerName . | Format-Table -Property DHCP*

Enabling DHCP on Each Adapter

To enable DHCP on all adapters, use the following command:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName . | ForEach-Object -Process {$_.EnableDHCP()}

You can use the Filter statement "IPEnabled=true and DHCPEnabled=false" to avoid enabling DHCP where it is already enabled, but omitting this step will not cause errors.

Releasing and Renewing DHCP Leases on Specific Adapters

The Win32_NetworkAdapterConfiguration class has ReleaseDHCPLease and RenewDHCPLease methods. Both are used in the same way. In general, use these methods if you only need to release or renew addresses for an adapter on a specific subnet. The easiest way to filter adapters on a subnet is to choose only the adapter configurations that use the gateway for that subnet. For example, the following command releases all DHCP leases on adapters on the local computer that are obtaining DHCP leases from 192.168.1.254:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true and DHCPEnabled=true" -ComputerName . | Where-Object -FilterScript {$_.DHCPServer -contains "192.168.1.254"} | ForEach-Object -Process {$_.ReleaseDHCPLease()}

The only change for renewing a DHCP lease is to use the RenewDHCPLease method instead of the ReleaseDHCPLease method:

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true and DHCPEnabled=true" -ComputerName . | Where-Object -FilterScript {$_.DHCPServer -contains "192.168.1.254"} | ForEach-Object -Process {$_.ReleaseDHCPLease()}
Note:

When using these methods on a remote computer, be aware that you can lose access to the remote system if you are connected to it through the adapter with the released or renewed lease.

Releasing and Renewing DHCP Leases on All Adapters

You can perform global DHCP address releases or renewals on all adapters by using the Win32_NetworkAdapterConfiguration methods, ReleaseDHCPLeaseAll and RenewDHCPLeaseAll. However, the command must apply to the WMI class, rather than a particular adapter, because releasing and renewing leases globally is performed on the class, not on a specific adapter.

You can get a reference to a WMI class, instead of class instances, by listing all WMI classes and then selecting only the desired class by name. For example, the following command returns the Win32_NetworkAdapterConfiguration class:

Get-WmiObject -List | Where-Object -FilterScript {$_.Name -eq "Win32_NetworkAdapterConfiguration"}

You can treat the entire command as the class and then invoke the ReleaseDHCPAdapterLease method on it. In the following command, the parentheses surrounding the Get-WmiObject and Where-Object pipeline elements direct Windows PowerShell to evaluate them first:

( Get-WmiObject -List | Where-Object -FilterScript {$_.Name -eq "Win32_NetworkAdapterConfiguration"} ).ReleaseDHCPLeaseAll()

You can use the same command format to invoke the RenewDHCPLeaseAll method:

( Get-WmiObject -List | Where-Object -FilterScript {$_.Name -eq "Win32_NetworkAdapterConfiguration"} ).RenewDHCPLeaseAll()

Creating a Network Share

To create a network share, use the Win32_Share Create method:

(Get-WmiObject -List -ComputerName . | Where-Object -FilterScript {$_.Name -eq "Win32_Share"}).Create("C:\temp","TempShare",0,25,"test share of the temp folder")

You can also create the share by using net share in Windows PowerShell:

net share tempshare=c:\temp /users:25 /remark:"test share of the temp folder"

Removing a Network Share

You can remove a network share with Win32_Share, but the process is slightly different from creating a share, because you need to retrieve the specific share to be removed, rather than the Win32_Share class. The following statement deletes the share "TempShare":

 (Get-WmiObject -Class Win32_Share -ComputerName . -Filter "Name='TempShare'").Delete()

Net share works as well:

PS> net share tempshare /delete
tempshare was deleted successfully.

Connecting a Windows Accessible Network Drive

The New-PSDrive cmdlets creates a Windows PowerShell drive, but drives created this way are available only to Windows PowerShell. To create a new networked drive, you can use the WScript.Network COM object. The following command maps the share \\FPS01\users to local drive B:

(New-Object -ComObject WScript.Network).MapNetworkDrive("B:", "\\FPS01\users")

The net use command works as well:

net use B: \\FPS01\users

Drives mapped with either WScript.Network or net use are immediately available to Windows PowerShell.


Working with Files and Folders

Navigating through Windows PowerShell drives and manipulating the items on them is similar to manipulating files and folders on Windows physical disk drives. We will discuss how to deal with specific file and folder manipulation tasks in this section.

Listing All the Files and Folders Within a Folder

You can get all items directly within a folder by using Get-ChildItem. Add the optional Force parameter to display hidden or system items. For example, this command displays the direct contents of Windows PowerShell Drive C (which is the same as the Windows physical drive C):

Get-ChildItem -Force C:\

The command lists only the directly contained items, much like using Cmd.exe's DIR command or ls in a UNIX shell. In order to show contained items, you need to specify the -Recurse parameter as well. (This can take an extremely long time to complete.) To list everything on the C drive:

Get-ChildItem -Force C:\ -Recurse

Get-ChildItem can filter items with its Path, Filter, Include, and Exclude parameters, but those are typically based only on name. You can perform complex filtering based on other properties of items by using Where-Object.

The following command finds all executables within the Program Files folder that were last modified after October 1, 2005 and which are neither smaller than 1 megabyte nor larger than 10 megabytes:

Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object -FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}

Copying Files and Folders

Copying is done with Copy-Item. The following command backs up C:\boot.ini to C:\boot.bak:

Copy-Item -Path c:\boot.ini -Destination c:\boot.bak

If the destination file already exists, the copy attempt fails. To overwrite a pre-existing destination, use the Force parameter:

Copy-Item -Path c:\boot.ini -Destination c:\boot.bak -Force

This command works even when the destination is read-only.

Folder copying works the same way. This command copies the folder C:\temp\test1 to the new folder c:\temp\DeleteMe recursively:

Copy-Item C:\temp\test1 -Recurse c:\temp\DeleteMe

You can also copy a selection of items. The following command copies all .txt files contained anywhere in c:\data to c:\temp\text:

Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination c:\temp\text

You can still use other tools to perform file system copies. XCOPY, ROBOCOPY, and COM objects, such as the Scripting.FileSystemObject, all work in Windows PowerShell. For example, you can use the Windows Script Host Scripting.FileSystem COM class to back up C:\boot.ini to C:\boot.bak:

(New-Object -ComObject Scripting.FileSystemObject).CopyFile("c:\boot.ini", "c:\boot.bak")

Creating Files and Folders

Creating new items works the same on all Windows PowerShell providers. If a Windows PowerShell provider has more than one type of item—for example, the FileSystem Windows PowerShell provider distinguishes between directories and files—you need to specify the item type.

This command creates a new folder C:\temp\New Folder:

New-Item -Path 'C:\temp\New Folder' -ItemType "directory"

This command creates a new empty file C:\temp\New Folder\file.txt

New-Item -Path 'C:\temp\New Folder\file.txt' -ItemType "file"

Removing All Files and Folders Within a Folder

You can remove contained items using Remove-Item, but you will be prompted to confirm the removal if the item contains anything else. For example, if you attempt to delete the folder C:\temp\DeleteMe that contains other items, Windows PowerShell prompts you for confirmation before deleting the folder:

Remove-Item C:\temp\DeleteMe

Confirm
The item at C:\temp\DeleteMe has children and the -recurse parameter was not
specified. If you continue, all children will be removed with the item. Are you
sure you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):

If you do not want to be prompted for each contained item, specify the Recurse parameter:

Remove-Item C:\temp\DeleteMe -Recurse

Mapping a Local Folder as a Windows Accessible Drive

You can also map a local folder, using the subst command. The following command creates a local drive P: rooted in the local Program Files directory:

subst p: $env:programfiles

Just as with network drives, drives mapped within Windows PowerShell using subst are immediately visible to the Windows PowerShell shell.

Reading a Text File into an Array

One of the more common storage formats for text data is in a file with separate lines treated as distinct data elements. The Get-Content cmdlet can be used to read an entire file in one step, as shown here:

PS> Get-Content -Path C:\boot.ini
[boot loader]
timeout=5
default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Professional"
 /noexecute=AlwaysOff /fastdetect
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS=" Microsoft Windows XP Professional
with Data Execution Prevention" /noexecute=optin /fastdetect

Get-Content already treats the data read from the file as an array, with one element per line of file content. You can confirm this by checking the Length of the returned content:

PS> (Get-Content -Path C:\boot.ini).Length
6

This command is most useful for getting lists of information into Windows PowerShell directly. For example, you might store a list of computer names or IP addresses in a file C:\temp\domainMembers.txt, with one name on each line of the file. You can use Get-Content to retrieve the file contents and put them in the variable $Computers:

$Computers = Get-Content -Path C:\temp\DomainMembers.txt

$Computers is now an array containing a computer name in each element.


Working with Registry Keys

Because registry keys are items on Windows PowerShell drives, working with them is very similar to working with files and folders. One critical difference is that every item on a registry-based Windows PowerShell drive is a container, just like a folder on a file system drive. However, registry entries and their associated values are properties of the items, not distinct items.

Listing All Subkeys of a Registry Key

You can show all items directly within a registry key by using Get-ChildItem. Add the optional Force parameter to display hidden or system items. For example, this command displays the items directly within Windows PowerShell drive HKCU:, which corresponds to the HKEY_CURRENT_USER registry hive:

PS> Get-ChildItem -Path hkcu:\

   Hive: Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER

SKC  VC Name                           Property
---  -- ----                           --------
  2   0 AppEvents                      {}
  7  33 Console                        {ColorTable00, ColorTable01, ColorTab...
 25   1 Control Panel                  {Opened}
  0   5 Environment                    {APR_ICONV_PATH, INCLUDE, LIB, TEMP...}
  1   7 Identities                     {Last Username, Last User ...
  4   0 Keyboard Layout                {}
...

These are the top-level keys visible under HKEY_CURRENT_USER in the Registry Editor (Regedit.exe).

You can also specify this registry path by specifying the registry provider's name, followed by "::". The registry provider's full name is Microsoft.PowerShell.Core\Registry, but this can be shortened to just Registry. Any of the following commands will list the contents directly under HKCU:

Get-ChildItem -Path Registry::HKEY_CURRENT_USER
Get-ChildItem -Path Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER
Get-ChildItem -Path Registry::HKCU
Get-ChildItem -Path Microsoft.PowerShell.Core\Registry::HKCU
Get-ChildItem HKCU:

These commands list only the directly contained items, much like using Cmd.exe's DIR command or ls in a UNIX shell. To show contained items, you need to specify the Recurse parameter. To list all registry keys in HKCU, use the following command (This operation can take an extremely long time.):

Get-ChildItem -Path hkcu:\ -Recurse

Get-ChildItem can perform complex filtering capabilities through its Path, Filter, Include, and Exclude parameters, but those parameters are typically based only on name. You can perform complex filtering based on other properties of items by using the Where-Objectcmdlet. The following command finds all keys within HKCU:\Software that have no more than one subkey and also have exactly four values:

Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object -FilterScript {($_.SubKeyCount -le 1) -and ($_.ValueCount -eq 4) }

Copying Keys

Copying is done with Copy-Item. The following command copies HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion and all of its properties to HKCU:\, creating a new key named "CurrentVersion":

Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu:

If you examine this new key in the registry editor or by using Get-ChildItem, you will notice that you do not have copies of the contained subkeys in the new location. In order to copy all of the contents of a container, you need to specify the Recurse parameter. To make the preceding copy command recursive, you would use this command:

Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu: -Recurse

You can still use other tools you already have available to perform filesystem copies. Any registry editing tools—including reg.exe, regini.exe, and regedit.exe—and COM objects that support registry editing (such as WScript.Shell and WMI's StdRegProv class) can be used from within Windows PowerShell.

Creating Keys

Creating new keys in the registry is simpler than creating a new item in a file system. Because all registry keys are containers, you do not need to specify the item type; you simply supply an explicit path, such as:

New-Item -Path hkcu:\software\_DeleteMe

You can also use a provider-based path to specify a key:

New-Item -Path Registry::HKCU\_DeleteMe

Deleting Keys

Deleting items is essentially the same for all providers. The following commands will silently remove items:

Remove-Item -Path hkcu:\Software\_DeleteMe
Remove-Item -Path 'hkcu:\key with spaces in the name'

Removing All Keys Under a Specific Key

You can remove contained items by using Remove-Item, but you will be prompted to confirm the removal if the item contains anything else. For example, if we attempt to delete the HKCU:\CurrentVersion subkey we created, we see this:

Remove-Item -Path hkcu:\CurrentVersion

Confirm
The item at HKCU:\CurrentVersion\AdminDebug has children and the -recurse
parameter was not specified. If you continue, all children will be removed with
 the item. Are you sure you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):

To delete contained items without prompting, specify the -Recurse parameter:

Remove-Item -Path HKCU:\CurrentVersion -Recurse

If you wanted to remove all items within HKCU:\CurrentVersion but not HKCU:\CurrentVersion itself, you could instead use:

Remove-Item -Path HKCU:\CurrentVersion\* -Recurse


Working with Registry Entries

Because registry entries are properties of keys and, as such, cannot be directly browsed, we need to take a slightly different approach when working with them.

Listing Registry Entries

There are many different ways to examine registry entries. The simplest way is to get the property names associated with a key. For example, to see the names of the entries in the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion, use Get-Item. Registry keys have a property with the generic name of "Property" that is a list of registry entries in the key. The following command selects the Property property and expands the items so that they are displayed in a list:

PS> Get-Item -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion | Select-Object -ExpandProperty Property
DevicePath
MediaPathUnexpanded
ProgramFilesDir
CommonFilesDir
ProductId

To view the registry entries in a more readable form, use Get-ItemProperty:

PS> Get-ItemProperty -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion

PSPath              : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SO
                      FTWARE\Microsoft\Windows\CurrentVersion
PSParentPath        : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SO
                      FTWARE\Microsoft\Windows
PSChildName         : CurrentVersion
PSDrive             : HKLM
PSProvider          : Microsoft.PowerShell.Core\Registry
DevicePath          : C:\WINDOWS\inf
MediaPathUnexpanded : C:\WINDOWS\Media
ProgramFilesDir     : C:\Program Files
CommonFilesDir      : C:\Program Files\Common Files
ProductId           : 76487-338-1167776-22465
WallPaperDir        : C:\WINDOWS\Web\Wallpaper
MediaPath           : C:\WINDOWS\Media
ProgramFilesPath    : C:\Program Files
PF_AccessoriesName  : Accessories
(default)           :

The Windows PowerShell-related properties for the key are all prefixed with "PS", such as PSPath, PSParentPath, PSChildName, and PSProvider.

You can use the "." notation for referring to the current location. You can use Set-Location to change to the CurrentVersion registry container first:

Set-Location -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion

Alternatively, you can use the built-in HKLM PSDrive with Set-Location:

Set-Location -Path hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion

You can then use the "." notation for the current location to list the properties without specifying a full path:

PS> Get-ItemProperty -Path .
...
DevicePath          : C:\WINDOWS\inf
MediaPathUnexpanded : C:\WINDOWS\Media
ProgramFilesDir     : C:\Program Files
...

Path expansion works the same as it does within the file system, so from this location you can get the ItemProperty listing for HKLM:\SOFTWARE\Microsoft\Windows\Help by using Get-ItemProperty -Path ..\Help.

Getting a Single Registry Entry

If you want to retrieve a specific entry in a registry key, you can use one of several possible approaches. This example finds the value of DevicePath in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion.

Using Get-ItemProperty, use the Path parameter to specify the name of the key, and the Name parameter to specify the name of the DevicePath entry.

PS> Get-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion -Name DevicePath

PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\
               Microsoft\Windows\CurrentVersion
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\
               Microsoft\Windows
PSChildName  : CurrentVersion
PSDrive      : HKLM
PSProvider   : Microsoft.PowerShell.Core\Registry
DevicePath   : C:\WINDOWS\inf

This command returns the standard Windows PowerShell properties as well as the DevicePath property.

Note:

Although Get-ItemProperty has Filter, Include, and Exclude parameters, they cannot be used to filter by property name. These parameters refer to registry keys—which are item paths—and not registry entries—which are item properties.

Another option is to use the Reg.exe command line tool. For help with reg.exe, type reg.exe /? at a command prompt. To find the DevicePath entry, use reg.exe as shown in the following command:

PS> reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion /v DevicePath

! REG.EXE VERSION 3.0

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion
    DevicePath  REG_EXPAND_SZ   %SystemRoot%\inf

You can also use the WshShell COM object as well to find some registry entries, although this method does not work with large binary data or with registry entry names that include characters such as "\"). Append the property name to the item path with a \ separator:

PS> (New-Object -ComObject WScript.Shell).RegRead("HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\DevicePath")
%SystemRoot%\inf

Creating New Registry Entries

To add a new entry named "PowerShellPath" to the CurrentVersion key, use New-ItemProperty with the path to the key, the entry name, and the value of the entry. For this example, we will take the value of the Windows PowerShell variable $PSHome, which stores the path to the installation directory for Windows PowerShell.

You can add the new entry to the key by using the following command, and the command also returns information about the new entry:

PS> New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -PropertyType String -Value $PSHome

PSPath         : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWAR
                 E\Microsoft\Windows\CurrentVersion
PSParentPath   : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWAR
                 E\Microsoft\Windows
PSChildName    : CurrentVersion
PSDrive        : HKLM
PSProvider     : Microsoft.PowerShell.Core\Registry
PowerShellPath : C:\Program Files\Windows PowerShell\v1.0

The PropertyType must be the name of a Microsoft.Win32.RegistryValueKind enumeration member from the following table:

PropertyType Value | Meaning
Binary | Binary data
DWord | A number that is a valid UInt32
ExpandString | A string that can contain environment variables that are dynamically expanded
MultiString | A multiline string
String | Any string value
QWord | 8 bytes of binary data
Note:

You can add a registry entry to multiple locations by specifying an array of values for the Path parameter:

New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion, HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -PropertyType String -Value $PSHome

You can also overwrite a pre-existing registry entry value by adding the Force parameter to any New-ItemProperty command.

Renaming Registry Entries

To rename the PowerShellPath entry to "PSHome," use Rename-ItemProperty:

Rename-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -NewName PSHome

To display the renamed value, add the PassThru parameter to the command.

Rename-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -NewName PSHome -passthru

Deleting Registry Entries

To delete both the PSHome and PowerShellPath registry entries, use Remove-ItemProperty:

Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PSHome
Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath


Running Remote Commands

You can run commands on one or hundreds of computers with a single Windows PowerShell command. Windows PowerShell supports remote computing by using various technologies, including WMI, RPC, and WS-Management.

Remoting Without Configuration

Many Windows PowerShell cmdlets have a ComputerName parameter that enables you to collect data and change settings one or more remote computers. They use a variety of communication technologies and many work on all Windows operating systems that Windows PowerShell supports without any special configuration.

These cmdlets include:

  • Restart-Computer

  • Test-Connection

  • Clear-EventLog

  • Get-EventLog

  • Get-Hotfix

  • Get-Process

  • Get-Service

  • Set-Service

  • Get-Hotfix

  • Get-WmiObject

Typically, cmdlets that support remoting without special configuration have a ComputerName parameter and do not have a Session parameter. To find these cmdlets in your session, type:

get-command | where { $_.parameters.keys -contains "ComputerName" -and $_.parameters.keys -notcontains "Session"}

Windows PowerShell Remoting

Windows PowerShell remoting, which uses the WS-Management protocol, lets you run any Windows PowerShell command on one or many remote computers. It lets you establish persistent connections, start 1:1 interactive sessions, and run scripts on multiple computers.

To use Windows PowerShell remoting, the remote computer must be configured for remote management. For more information, including instructions, see about_Remote_Requirements.

After you have configured Windows PowerShell remoting, many remoting strategies are available to you. The remainder of this document lists just a few of them. For more information, see about_Remote and about_Remote_FAQ.

Start an Interactive Session

To start an interactive session with a single remote computer, use the Enter-PSSession cmdlet. For example, to start an interactive session with the Server01 remote computer, type:

enter-pssession Server01

The command prompt changes to display the name of the computer to which you are connected. From then on, any commands that you type at the prompt run on the remote computer and the results are displayed on the local computer.

To end the interactive session, type:

exit-pssession

For more information about the Enter-PSSession and Exit-PSSession cmdlets, see Enter-PSSession and Exit-PSSession.

Run a Remote Command

To run any command on one or many remote computers, use the Invoke-Command cmdlet. For example, to run a Get-UICulture command on the Server01 and Server02 remote computers, type:

invoke-command -computername Server01, Server02 {get-UICulture}

The output is returned to your computer.

LCID    Name     DisplayName               PSComputerName
----    ----     -----------               --------------
1033    en-US    English (United States)   server01.corp.fabrikam.com
1033    en-US    English (United States)   server02.corp.fabrikam.com

For more information about the Invoke-Command cmdlet, see Invoke-Command.

Run a Script

To run a script on one or many remote computers, use the FilePath parameter of the Invoke-Command cmdlet. The script must be on or accessible to your local computer. The results are returned to your local computer.

For example, the following command runs the DiskCollect.ps1 script on the Server01 and Server02 remote computers.

invoke-command -computername Server01, Server02 -filepath c:\Scripts\DiskCollect.ps1

For more information about the Invoke-Command cmdlet, see Invoke-Command.

Establish a Persistent Connection

To run a series of related commands that share data, create a session on the remote computer and then use the Invoke-Command cmdlet to run commands in the session that you create. To create a remote session, use the New-PSSession cmdlet.

For example, the following command creates a remote session on the Server01 computer and another remote session on the Server02 computer. It saves the session objects in the $s variable.

$s = new-pssession -computername Server01, Server02

Now that the sessions are established, you can run any command in them. And because the sessions are persistent, you can collect data in one command and use it in a subsequent command.

For example, the following command runs a Get-Hotfix command in the sessions in the $s variable and it saves the results in the $h variable. The $h variable is created in each of the sessions in $s, but it does not exist in the local session.

invoke-command -session $s {$h = get-hotfix}

Now you can use the data in the $h variable in subsequent commands, such as the following one. The results are displayed on the local computer.

invoke-command -session $s {$h | where {$_.installedby -ne "NTAUTHORITY\SYSTEM"

Advanced Remoting

Windows PowerShell remote management just begins here. By using the cmdlets installed with Windows PowerShell, you can establish and configure remote sessions both from the local and remote ends, create customized and restricted sessions, allow users to import commands from a remote session that actually run implicitly on the remote session, configure the security of a remote session, and much more.

To facilitate remote configuration, Windows PowerShell includes a WS-Management provider. The WSMAN: drive that the provider creates lets you navigate through a hierarchy of configuration settings on the local computer and remote computers. For more information the WS-Management provider, see WS-Management Provider and about_WS-Management_Cmdlets, or in the Windows PowerShell console, type "get-help wsman".

For more information, see about_Remote_FAQ, New-PSSessionConfiguration, and Import-PSSession. For help with remoting errors, see about_Remote_Troubleshooting.

See Also

    New-PSSessionConfiguration
  • about_Remote
  • about_Remote_FAQ
  • about_Remote_Requirements
  • about_Remote_Troubleshooting
  • about_PSSessions
  • about_WS-Management_Cmdlets
  • Invoke-Command
  • Import-PSSession
  • New-PSSession
  • WS-Management Provider


Appendix 1 - Compatibility Aliases

Windows PowerShell has several transition aliases that allow UNIX and Cmd users to use familiar command names in Windows PowerShell. The most common aliases are shown in the table below, along with the Windows PowerShell command behind the alias and the standard Windows PowerShell alias if one exists.

You can find the Windows PowerShell command that any alias points to from within Windows PowerShell by using the Get-Alias cmdlet. For example, type get-alias cls.

CommandType     Name                            Definition
-----------     ----                            ----------
Alias           cls                             Clear-Host

CMD Command | UNIX Command | PS Command | PS Alias
dir | ls | Get-ChildItem | gci
cls | clear | Clear-Host (function) | N/A
del, erase, rmdir | rm | Remove-Item | ri
copy | cp | Copy-Item | ci
move | mv | Move-Item | mi
rename | mv | Rename-Item | rni
type | cat | Get-Content | gc
cd | cd | Set-Location | sl
md | mkdir | New-Item | ni
N/A | pushd | Push-Location | N/A
N/A | popd | Pop-Location | N/A


Appendix 2 - Creating a Custom PowerShell Shortcut

The following procedure describes how to create a shortcut to Windows PowerShell that has several convenient options customized.

  1. Create a shortcut that points to Powershell.exe.

  2. Right-click the shortcut, and then click Properties.

  3. Click the Options tab.

  4. In the Edit Options section, select the QuickEdit check box.

    This setting lets you select text in the Windows PowerShell console window by dragging the left mouse button, and it lets you copy text to the clipboard by pressing ENTER or by right-clicking the mouse.

  5. In the Edit Options section, select the Insert Mode check box. This setting lets you right-click in the console window to automatically paste text from the clipboard.

  6. In the Command History section, type or select a number between 1 and 999 in the Buffer Size box. This sets the number of typed commands that will be kept in the console buffer.

  7. In the Command History section, select the Discard Old Duplicates check box to eliminate repeated commands from the console buffer.

  8. Click the Layout tab.

  9. In the Screen Buffer section, type a number between 1 and 9999 in the Height box. The height represents the number of lines of output that are buffered. This is the maximum number of lines retained for viewing when you scroll through the console window. If this number is lower than the height shown in the Window size section, the window size height will automatically be reduced to the same value.

  10. In the Window Size section, type a number between 1 and 9999 for the width. This represents the number of characters that are displayed across the console window. The default width is 80, and Windows PowerShell's output formatting is designed for this width.

  11. If you want to place the console at a particular point on the desktop when it is opened, clear the Let system position window check box in the Window position section, and then change the values in the Left and Top boxes in the Window position section.

  12. Click OK.


Windows PowerShell About Help Topics

This section contains the conceptual ("about") help topics in Windows PowerShell.

Topic | Description
about_Aliases | Describes alternate names for cmdlets and commands in Windows PowerShell.
about_Arithmetic_Operators | Describes the operators that perform arithmetic in Windows PowerShell.
about_Arrays | Describes arrays; a compact data structure for storing data elements.
about_Assignment_Operators | Describes the operators that assign values to variables.
about_Automatic_Variables | Describes the automatic variables, which that store state information for Windows PowerShell.
about_Break | Explains how to use the Break statement, a statement that immediately exits Foreach, For, While, Do, and Switch statements.
about_Command_Precedence | Explains how Windows PowerShell finds commands.
about_Command_Syntax | Explains the command format in Windows PowerShell.
about_Comment_Based_Help | Explains how to write comment-based help topics for functions and scripts.
about_CommonParameters | Describes parameters that can be used with any cmdlet.
about_Comparison_Operators | Describes the operators that compare values in Windows PowerShell.
about_Continue | Describes the Continue statement, which immediately returns to top of a program loop.
about_Core_Commands | Lists the cmdlets designed for use with Windows PowerShell providers.
about_Data_Sections | Describes the Data section of scripts, which is designed to isolate data from code logic.
about_Debuggers | Describes the Windows PowerShell script debugger, a set of cmdlets for debugging scripts and functions.
about_Do | Describes the Do statement, which runs a script block one or more times subject to a While or Until condition.
about_Environment_Variables | Explains how to access Windows environment variables in Windows PowerShell.
about_Escape_Characters | Introduces the escape character in Windows PowerShell (`) and explains its effect.
about_EventLogs | Describes the Windows PowerShell event log in Event Viewer.
about_Execution_Policies | Describes the Windows PowerShell execution policies and explains how to manage them.
about_For | Describes the For loop in Windows PowerShell.
about_Foreach | Describes the ForEach statement, a statement that acts on each item in a collection.
about_Format.ps1xml | Describes the Format.ps1xml files that define the default display of objects in the console.
about_Functions | Explains how to create and use functions in Windows PowerShell.
about_Functions_Advanced | Introduction to advanced functions; the functions that act like cmdlets.
about_Functions_Advanced_Methods | Explains how to use the methods and properties that are available to cmdlets in advanced functions.
about_Functions_Advanced_Parameters | Shows how to declare parameters for advanced functions.
about_Functions_CmdletBindingAttribute | Describes the CmdletBinding attribute, which identifies a function that works like a cmdlet.
about_Hash_Tables | Explains how to create, use, and sort hash tables in Windows PowerShell.
about_History | Explains how to get and run commands from the command history.
about_If | Describes the If statement, which establishes conditions for an action.
about_Jobs | Describes Windows PowerShell background jobs.
about_Job_Details | Provides detailed information about background jobs.
about_Join | Describes the Join operator, which combines multiple strings into a single string.
about_Language_Keywords | Describes the keywords in the Windows PowerShell scripting language.
about_Line_Editing | Describes the editing features of the Windows PowerShell console.
about_Locations | Explains how to use the working location in Windows PowerShell.
about_Logical_Operators | Describes the operators that connect statements in Windows PowerShell.
about_Methods | Explains how to use methods to perform actions on objects in Windows PowerShell.
about_Modules | Explains how to install, import, and use Windows PowerShell modules.
about_Objects | Explains how to work with objects in Windows PowerShell.
about_Operators | The overview topic that describes operators in Windows PowerShell. Contains topics about each operator type.
about_Parameters | Explains how to working with cmdlet parameters in Windows PowerShell.
about_Parsing | Explains how Windows PowerShell parses commands.
about_Path_Syntax | Describes full and relative path name formats in Windows PowerShell.
about_Pipelines | Explains how to combine commands into pipelines in Windows PowerShell.
about_Preference_Variables | Describes the preference variables that customize Windows PowerShell.
about_Profiles | Explains how to create and use a Windows PowerShell profile.
about_Prompts | Explains how to create and use a Windows PowerShell profile.
about_Properties | Explains how to use object properties in Windows PowerShell.
about_Providers | Describes the Windows PowerShell providers and explains how to use the data that they expose.
about_PSSessions | Describes Windows PowerShell sessions (PSSessions) and explains how to use them to run remote commands.
about_PSSession_Details | Provides detailed information about Windows PowerShell sessions.
about_PSSnapins | Describes Windows PowerShell snap-ins and explains how to use them to extend Windows PowerShell.
about_Quoting_Rules | Explains the rules for using single and double quotation marks in Windows PowerShell, including here-strings.
about_Redirection | Explains how to redirect output to variables and text files. Includes redirection operators.
about_Ref | Explains how to create and use a reference variable type.
about_Regular_Expressions | Explains how to use regular expressions in Windows PowerShell.
about_Remote | How to run remote commands in Windows PowerShell.
about_Remote_FAQ | Questions and answers about running remote commands in Windows PowerShell.
about_Remote_Jobs | Explains how to run background jobs on remote computers
about_Remote_Output | Interpreting and formatting the output of remote commands.
about_Remote_Requirements | System requirements and configuration requirements for running remote commands in Windows PowerShell.
about_Remote_Troubleshooting | Troubleshooting remote operations in Windows PowerShell.
about_Requires | Describes the Requires statement, which prevents a script from running without required snap-ins and versions.
about_Reserved_Words | Lists words that are reserved to Windows PowerShell.
about_Return | Exits the current scope, which can be a function, script, or script block.
about_Scopes | Explains how to set and change the scope of functions and variables in Windows PowerShell.
about_Script_Blocks | Explains how to use script blocks to combine expressions, statements and commands into a single code block.
about_Script_Internationalization | Describes the features that make it easy for scripts to display user messages in the language selected for Windows.
about_Scripts | Explains how to write and run scripts in Windows PowerShell.
about_Session_Configurations | Describes session configurations, which determine the users who can connect to the computer remotely and the commands they can run.
about_Signing | Describes the Windows PowerShell execution policies, explains how to manage them, and explains to how sign scripts so they comply with the execution policies.
about_Special_Characters | Describes the special characters in Windows PowerShell.
about_Split | Describes the Split operator, which splits strings into substrings.
about_Switch | Explains how to use a switch statement to replace multiple If statements.
about_Throw | Describes the Throw keyword, which generates a terminating error.
about_Transactions | Explains how to manage transacted operations in Windows PowerShell.
about_Trap | Describes the Trap keyword, which handles a terminating error.
about_Try_Catch_Finally | Error handling in scripts is done using the Try, Catch, and Finally script blocks.
about_Types.ps1xml | Describes the Types.ps1xml files that let you extend the .NET types of objects used in Windows PowerShell.
about_Type_Operators | Describes the operators that work with .NET types.
about_Variables | An overview topic that explains the types of variables in Windows PowerShell.
about_While | Describes While loops in Windows PowerShell.
about_Wildcards | Explains how to use the wildcard character (*) in Windows PowerShell.
about_Windows_PowerShell_2.0 | Describes the features introduced in the Windows PowerShell 2.0.
about_Windows_PowerShell_ISE | Describes the Windows PowerShell Integrated Scripting Environment.
about_WMI_Cmdlets | Provides background information about Windows Management Instrumentation (WMI) and Windows PowerShell.
about_WS-Management_Cmdlets | Provides an overview of Web Services for Management (WS-Management) as background for using the WS-Management cmdlets in Windows PowerShell.

See Also

  • Windows PowerShell Cmdlet Help Topics
  • Windows PowerShell Provider Help Topics
  • PowerShell.exe Console Help
  • Windows PowerShell SDK


about_Aliases

TOPIC
    about_aliases

SHORT DESCRIPTION
    Describes how to use alternate names for cmdlets and commands in Windows
    PowerShell.

LONG DESCRIPTION
    An alias is an alternate name or nickname for a cmdlet or for a command
    element, such as a function, script, file, or executable file. You
    can use the alias instead of the command name in any Windows PowerShell
    commands.

    To create an alias, use the New-Alias cmdlet. For example, the following
    command creates the "gas" alias for the Get-AuthenticodeSignature cmdlet:

        new-alias -name gas -value Get-AuthenticodeSignature

    After you create the alias for the cmdlet name, you can use the alias
    instead of the cmdlet name. For example, to get the Authenticode signature
    for the SqlScript.ps1 file, type:

        get-authenticodesignature sqlscript.ps1

    Or, type:

        gas sqlscript.ps1

    If you create "word" as the alias for Microsoft Office Word, you can type
    "word" instead of the following:

        "c:\program files\microsoft office\office11\winword.exe"

BUILT-IN ALIASES
    Windows PowerShell includes a set of built-in aliases, including "cd" and
    "chdir" for the Set-Location cmdlet, and "ls" and "dir" for the
    Get-ChildItem cmdlet.

    To get all the aliases on the computer, including the built-in aliases,
    type:

        get-alias

ALIAS CMDLETS
    Windows PowerShell includes the following cmdlets, which are designed for
    working with aliases:

        - Get-Alias. Gets all the aliases in the current session.
        - New-Alias. Creates a new alias.
        - Set-Alias. Creates or changes an alias.
        - Export-Alias. Exports one or more aliases to a file.
        - Import-Alias. Imports an alias file into Windows PowerShell.

    For detailed information about the cmdlets, type:

    get-help <cmdlet-name> -detailed

    For example, type:

    get-help export-alias -detailed

CREATING AN ALIAS
    To create a new alias, use the New-Alias cmdlet. For example, to create the
    "gh" alias for Get-Help, type:

    new-alias -name gh -value get-help

    You can use the alias in commands, just as you would use the full cmdlet
    name, and you can use the alias with parameters.

    For example, to get detailed Help for the Get-WmiObject cmdlet, type:

    get-help get-wmiobject -detailed

    Or, type:

    gh get-wmiobject -detailed

SAVING ALIASES
    The aliases that you create are saved only in the current session. To use
    the aliases in a different session, add the alias to your Windows
    PowerShell profile. Or, use the Export-Alias cmdlet to save the aliases to
    a file.

    For more information, type:

        get-help about_profile

GETTING ALIASES
    To get all the aliases in the current session, including the built-in
    aliases, the aliases in your Windows PowerShell profiles, and the aliases
    that you have created in the current session, type:

    get-alias

    To get particular aliases, use the Name parameter of the Get-Alias cmdlet.
    For example, to get aliases that begin with "p", type:

    get-alias -name p*

    To get the aliases for a particular item, use the Definition parameter.
    For example, to get the aliases for the Get-ChildItem cmdlet type:

    get-alias -definition Get-ChildItem

ALTERNATE NAMES FOR COMMANDS WITH PARAMETERS
    You can assign an alias to a cmdlet, script, function, or executable file.
    However, you cannot assign an alias to a command and its parameters.
    For example, you can assign an alias to the Get-EventLog cmdlet, but you
    cannot assign an alias to the "get-eventlog -logname system" command.

    However, you can create a function that includes the command. To create a
    function, type the word "function" followed by a name for the function.
    Type the command, and enclose it in braces ({}).

    For example, the following command creates the syslog function. This
    function represents the "get-eventlog -logname system" command:

    function syslog {get-eventlog -logname system}

    You can now type "syslog" instead of the command. And, you can create
    aliases for the syslog function.

    For more information about functions, type:

    get-help about_functions

ALIAS OBJECTS
     Windows PowerShell aliases are represented by objects that are instances
     of the System.Management.Automation.AliasInfo class. For more information
     about this type of object, see "AliasInfo Class" in the Microsoft
     Developer Network (MSDN) library at
     http://go.microsoft.com/fwlink/?LinkId=143644.

     To view the properties and methods of the alias objects, get the
     aliases. Then, pipe them to the Get-Member cmdlet. For example:

    get-alias | get-member

     To view the values of the properties of a specific alias, such as the
     "dir" alias, get the alias. Then, pipe it to the Format-List cmdlet. For
     example, the following command gets the "dir" alias. Next, the command
     pipes the alias to the Format-List cmdlet. Then, the command uses the
     Property parameter of Format-List with a wildcard character (*) to display
     all the properties of the "dir" alias. The following command performs
     these tasks:

    get-alias -name dir | format-list -property *

WINDOWS POWERSHELL ALIAS PROVIDER
    Windows PowerShell includes the Alias provider. The Alias provider lets you
    view the aliases in Windows PowerShell as though they were on a file system
    drive.

    The Alias provider exposes the Alias: drive. To go into the Alias: drive,
    type:

    set-location alias:

    To view the contents of the drive, type:

    get-childitem

    To view the contents of the drive from another Windows PowerShell drive,
    begin the path with the drive name. Include the colon (:). For example:

    get-childitem -path alias:

    To get information about a particular alias, type the drive name and
    the alias name. Or, type a name pattern. For example, to get all the
    aliases that begin with "p", type:

    get-childitem -path alias:p*

    For more information about the Windows PowerShell Alias provider,
    type:

    get-help alias-psprovider

SEE ALSO

    new-alias
    get-alias
    set-alias
    export-alias
    import-alias
    get-psprovider
    get-psdrive
    about_functions
    about_profiles
    about_providers


about_Arithmetic_Operators

TOPIC
    about_Arithmetic_Operators

SHORT DESCRIPTION
    Describes the operators that perform arithmetic in Windows PowerShell.

LONG DESCRIPTION

    Arithmetic operators calculate numeric values. You can use one or
    more arithmetic operators to add, subtract, multiply, and divide
    values, and to calculate the remainder (modulus) of a division operation.

    In addition, the addition operator (+) and multiplication operator (*)
    also operate on strings, arrays, and hash tables. The addition operator
    concatenates the input. The multiplication operator returns multiple copies
    of the input. You can even mix object types in an arithmetic statement.
    The method that is used to evaluate the statement is determined by the type
    of the leftmost object in the expression.

    Windows PowerShell supports the following arithmetic operators:

    Operator  Description                             Example
    --------  -----------                             -------
    +         Adds integers; concatenates strings,    6+2
              arrays, and hash tables.                "file" + "name"

    -         Subtracts one value from another        6-2
              value.                                  (get-date).date - 1

    -         Makes a number a negative number.       -6+2
                                                      -4

    *         Multiplies integers; copies strings     6*2
              and arrays the specified number of      "w" * 3
              times.

    /         Divides two values.                     6/2

    %         Returns the remainder of a division     7%2
              operation.

    OPERATOR PRECEDENCE
    Windows PowerShell processes arithmetic operators in the following order:

        Parentheses ()
        - (for a negative number)
        *, /, %
        +, - (for subtraction)

    Windows PowerShell processes the expressions from left to right according
    to the precedence rules. The following examples show the effect of the
    precedence rules:

        C:\PS> 3+6/3*4
        11

        C:\PS> 10+4/2
        12

        C:\PS> (10+4)/2
        7

        C:\PS> (3+3)/ (1+1)
        3

    The order in which Windows PowerShell evaluates expressions might differ
    from other programming and scripting languages that you have used. The
    following example shows a complicated assignment statement.

        C:\PS> $a = 0
        C:\PS> $b = 1,2
        C:\PS> $c = -1,-2

        C:\PS> $b[$a] = $c[$a++]

        C:\PS> $b
        1
        -1

    In this example, the expression $a++ is evaluated before $c[$a++].
    Evaluating $a++ changes the value of $a. The variable $a in $b[$a]
    equals 1, not 0, so the statement assigns a value to $b[1], not $b[0].

    ADDING AND MULTIPLYING NON-NUMERIC TYPES
    You can add numbers, strings, arrays, and hash tables. And, you can
    multiply numbers, strings, and arrays. However, you cannot multiply hash
    tables.

    When you add strings, arrays, or hash tables, the elements are
    concatenated. When you concatenate collections, such as arrays or hash
    tables, a new object is created that contains the objects from both
    collections. If you try to concatenate hash tables that have the same key,
    the operation fails.

    For example, the following commands create two arrays and then add them:

    C:\PS> $a = 1,2,3
    C:\PS> $b = "A","B,"C"
    C:\PS> $a + $b
    1
    2
    3
    A
    B
    C

    You can also perform arithmetic operations on objects of different types.
    The operation that Windows PowerShell performs is determined by the
    Microsoft .NET Framework type of the leftmost object in the operation.
    Windows PowerShell tries to convert all the objects in the operation to the
    .NET Framework type of the first
    object. If it succeeds in converting the objects, it performs the operation
    appropriate to the .NET Framework type of the first object. If it fails to
    convert any of the objects, the operation fails.

    The following example demonstrates the use of the addition and
    multiplication operators in operations that include different object types:

        C:\PS> "file" + 16
        file16

        C:\PS> $array = 1,2,3
        C:\PS> $array + 16
        1
        2
        3
        16

    C:\PS> $array + "file"
        1
        2
        3
        file

        C:\PS> "file" * 3
        filefilefile

    Because the method that is used to evaluate statements is determined by the
    leftmost object, addition and multiplication in Windows PowerShell are not
    strictly commutative. For example, (a + b) does not always equal (b + a),
    and (a * b) does not always equal (b * a).

    The following examples demonstrate this principle:

        C:\PS> "file" + 2
        file2

        C:\PS> 2 + "file"
        Cannot convert value "file" to type "System.Int32". Error: "Input
        string was not in a correct format."
        At line:1 char:4
        + 2 + <<<<  "file"

        C:\PS> "file" * 3
        filefilefile

        C:\PS> 3 * "file"
        Cannot convert value "file" to type "System.Int32". Error: "Input
        string was not in a correct format."
        At line:1 char:4
        + 3 * <<<<  "file"

    Hash tables are a slightly different case. You can add hash tables. And,
    you can add a hash table to an array. However, you cannot add any other
    type to a hash table.

    The following examples show how to add hash tables to each other and to
    other objects:

        C:\PS> $hash1 = @{a=1; b=2; c=3}
        C:\PS> $hash2 = @{c1="Server01"; c2="Server02"}
        C:\PS> $hash1 + $hash2

        Name                           Value
        ----                           -----
        c2                             Server02
        a                              1
        b                              2
        c1                             Server01
        c                              3

        C:\PS> $hash1 + 2
        You can add another hash table only to a hash table.
        At line:1 char:9
        + $hash1 + <<<<  2

        C:\PS> 2 + $hash1
        Cannot convert "System.Collections.Hashtable" to "System.Int32".
        At line:1 char:4
        + 2 + <<<<  $hash1

    The following examples demonstrate that you can add a hash table to an
    array. The entire hash table is added to the array as a single object.

        C:\PS> $array = 1,2,3
        C:\PS> $array + $hash1
        1
        2
        3

        Name                           Value
        ----                           -----
        a                              1
        b                              2
        c                              3

        C:\PS> $sum = $array + $hash1
        C:\PS> $sum.count
        4

        C:\PS> $sum[3]
        Name                           Value
        ----                           -----
        a                              1
        b                              2
        c                              3

        PS C:\ps-test> $sum + $hash2
        1
        2
        3

        Name                           Value
        ----                           -----
        a                              1
        b                              2
        c                              3
        c2                             Server02

    The following example shows that you cannot add hash tables that contain
    the same key:

        C:\PS> $hash1 = @{a=1; b=2; c=3}
        C:\PS> $hash2 = @{c="red"}
        C:\PS> $hash1 + $hash2
        Bad argument to operator '+': Item has already been added.
        Key in dictionary: 'c'    Key being added: 'c'.
        At line:1 char:9
        + $hash1 + <<<<  $hash2

    Although the addition operators are very useful, use the assignment
    operators to add elements to hash tables and arrays. For more information
    see about_assignment_operators. The following examples use the +=
    assignment operator to add items to an array:

        C:\PS>  $array
        1
        2
        3

        C:\PS>  $array + "file"
        1
        2
        3
        file

        C:\PS>  $array
        1
        2
        3

        C:\PS>  $array += "file"
        C:\PS>  $array
        1
        2
        3
        file

        C:\PS> $hash1

        Name                           Value
        ----                           -----
        a                              1
        b                              2
        c                              3

        C:\PS> $hash1 += @{e = 5}
        C:\PS> $hash1

        Name                           Value
        ----                           -----
        a                              1
        b                              2
        e                              5
        c                              3

    Windows PowerShell automatically selects the .NET Framework numeric type
    that best expresses the result without losing  precision. For example:

        C:\PS> 2 + 3.1
        5.1
        C:\PS> (2). GetType().FullName
        System.Int32
        C:\PS> (2 + 3.1).GetType().FullName
        System.Double

    If the result of an operation is too large for the type, the type of the
    result is widened to accommodate the result, as in the following example:

        C:\PS> (512MB).GetType().FullName
        System.Int32
        C:\PS> (512MB * 512MB).GetType().FullName
        System.Double

    The type of the result will not necessarily be the same as one of the
    operands. In the following example, the negative value cannot be cast to an
    unsigned integer, and the unsigned integer is too large to be cast to
    Int32:

        C:\PS> ([int32]::minvalue + [uint32]::maxvalue).gettype().fullname
        System.Int64

    In this example, Int64 can accommodate both types.

    The System.Decimal type is an exception. If either operand has the Decimal
    type, the result will be of the Decimal type. If the result is too large
    for the Decimal type, it will not be cast to Double. Instead, an error
    results.

        C:\PS> [Decimal]::maxvalue
        79228162514264337593543950335
        C:\PS> [Decimal]::maxvalue + 1
        Value was either too large or too small for a Decimal.
        At line:1 char:22
        + [Decimal]::maxvalue + <<<<  1

    ARITHMETIC OPERATORS AND VARIABLES
    You can also use arithmetic operators with variables. The operators act on
    the values of the variables. The following examples demonstrate the use of
    arithmetic operators with variables:

        C:\PS> $intA = 6
        C:\PS> $intB = 4
        C:\PS> $intA + $intB

        10

        C:\PS> $a = "Windows "
        C:\PS> $b = "PowerShell "
        C:\PS> $c = 2
    C:\PS> $a + $b + $c

        Windows PowerShell 2

    ARITHMETIC OPERATORS AND COMMANDS
    Typically, you use the arithmetic operators in expressions with numbers,
    strings, and arrays. However, you can also use arithmetic operators with
    the objects that commands return and with the properties of those objects.

    The following examples show how to use the arithmetic operators in
    expressions with Windows PowerShell commands:

    C:\PS> get-date
    Wednesday, January 02, 2008 1:28:42 PM

    C:\PS> $day = new-timespan -day 1
    C:\PS> get-date + $day
    Thursday, January 03, 2008 1:34:52 PM

    C:\PS> get-process | where {($_.ws * 2) -gt 50mb}
    Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
    -------  ------    -----      ----- -----   ------     -- -----------
       1896      39    50968      30620   264 1,572.55   1104 explorer
      12802      78   188468      81032   753 3,676.39   5676 OUTLOOK
        660       9    36168      26956   143    12.20    988 powershell
        561      14     6592      28144   110 1,010.09    496 services
       3476      80    34664      26092   234 ...45.69    876 svchost
        967      30    58804      59496   416   930.97   2508 WINWORD

EXAMPLES
    The following examples show how to use the arithmetic operators in
    Windows PowerShell:

    C:\PS> 1 + 1
    2

    C:\PS> 1 - 1
    0

    C:\PS> -(6 + 3)
    -9

    C:\PS> 6 * 2
    12

    C:\PS> 7 / 2
    3.5

    C:\PS> 7 % 2
    1

    C:\PS> w * 3
    www

    C:\PS> 3 * "w"
    Cannot convert value "w" to type "System.Int32". Error: "Input string was not
        in a correct format."
    At line:1 char:4
    + 3 * <<<< "w"

    PS C:\ps-test> "Windows" + " " + "PowerShell"
    Windows PowerShell

    PS C:\ps-test> $a = "Windows" + " " + "PowerShell"
    PS C:\ps-test> $a
    Windows PowerShell

    C:\PS> $a[0]
    W

    C:\PS> $a = "TestFiles.txt"
    C:\PS> $b = "C:\Logs\"
    C:\PS> $b + $a
    C:\Logs\TestFiles.txt

    C:\PS> $a = 1,2,3
    C:\PS> $a + 4
    1
    2
    3
    4

    C:\PS> $servers = @{0 = "LocalHost"; 1 = "Server01"; 2 = "Server02"}
    C:\PS> $servers + @{3 = "Server03"}
    Name Value
    ---- -----
    3 Server03
    2 Server02
    1 Server01
    0 LocalHost

    C:\PS> $servers
    Name Value
    ---- -----
    2 Server02
    1 Server01
    0 LocalHost

    C:\PS> $servers += @{3 = "Server03"} #Use assignment operator
    C:\PS> $servers
    Name Value
    ---- -----
    3 Server03
    2 Server02
    1 Server01
    0 LocalHost

SEE ALSO
    about_arrays
    about_assignment_operators
    about_comparison_operators
    about_hash_tables
    about_operators
    about_variables
    Get-Date
    New-TimeSpan


about_Arrays

TOPIC
    about_Arrays

SHORT DESCRIPTION
    Describes a compact data structure for storing data elements.

LONG DESCRIPTION
    An array is a data structure for storing a collection of data elements
    of the same type. Windows PowerShell supports data elements, such as
    string, int (32-bit integer), long (64-bit integer), bool (Boolean), byte,
    and other Microsoft .NET Framework object types.

  CREATING AND INITIALIZING AN ARRAY
    To create and initialize an array, assign multiple values to a variable.
    The values stored in the array are delimited with a comma and separated
    from the variable name by the assignment operator (=).

    For example, to create an array named $A that contains the seven
    numeric (int) values of 22, 5, 10, 8, 12, 9, and 80, type:

        $A = 22,5,10,8,12,9,80

    You can also create and initialize an array by using the range
    operator (..). For example, to create and initialize an array named
    "$B" that contains the values 5 through 8, type:

        $B = 5..8

    As a result, $B contains four values: 5, 6, 7, and 8.

    When no data type is specified, Windows PowerShell creates each array as
    an object array (type: object[]). To determine the data type of an array,
    use the GetType() method. For example, to determine the data type of the
    $a array, type:

        $a.gettype()

    To create a strongly typed array, that is, an array that can contain only
    values of a particular type, cast the variable as an array type, such
    as string[], long[], or int32[]. To cast an array, precede the variable
    name with an array type enclosed in brackets. For example, to create a
    32-bit integer array named $ia containing four integers (1500, 2230, 3350,
    and 4000), type:

        [int32[]]$ia = 1500,2230,3350,4000

    As a result, the $ia array can contain only integers.

    You can create arrays that are cast to any supported type in the
    Microsoft .NET Framework. For example, the objects that Get-Process
    retrieves to represent processes are of the System.Diagnostics.Process
    type. To create a strongly typed array of process objects, enter the
    following command:

        [Diagnostics.Process[]]$zz = Get-Process

    You can populate an array by using the output of a cmdlet, function, or
    statement. For example, the following statement creates an array that
    contains the processes that start with the letters "co" and that are
    running on the current computer:

        $LocalProcesses = get-process co*

    If the statement gets only a single process, the $LocalProcesses variable
    would not be an array. To ensure the command creates an array, use the
    array subexpression operator, @, as shown in the following example:

        $LocalProcesses = @(get-process co*)

    Even if the command returns a single process, the $LocalProcesses variable
    is an array. Even if it has only one member, you can treat it like any
    other array. For example, you can add other objects to it. For more
    information, see about_Operators.

  READING AN ARRAY
    You can refer to an array by using its variable name, such as $A or $a.
    Windows PowerShell is not case-sensitive.

    To display all the elements in the array, type the array name. For example:

    $a

    You can refer to the elements in an array by using an index, beginning
    at position 0. Enclose the index number in brackets. For example,
    to display the first element in the $a array, type:

        $a[0]

    To display the third element in the $a array, type:

        $a[2]

    Negative numbers count from the end of the array. For example, "-1"
    refers to the last element of the array. To display the last three elements
    of the array, type:

        $a[-3..-1]

    However, be cautious when using this notation.

        $a[0..-2]

    This command does not refer to all the elements of the array, except for
    the last one. It refers to the first, last, and second-to-last elements
    in the array.

    You can use the range operator to display a subset of all the values in an
    array. For example, to display the data elements at index position 1
    through 3, type:

        $a[1..3]

    You can use the plus operator (+) to combine a range with a list of
    elements in an array. For example, to display the elements at index
    positions 0, 2, and 4 through 6, type:

        $a[0,2+4..6]

    To determine how many items are in an array, combine the range with the
    length property of an array. For example, to display the elements from
    index position 2 to the end of the array, type:

        $a[2..($a.length-1)]

    The length is set to -1 because the index begins at position 0. Therefore,
    in a three-element array (1,2,3), the index of the third element is 2,
    which is one less than the length of the array.

    You can also use looping constructs, such as Foreach, For, and While loops,
    to refer to the elements in an array. For example, to use a Foreach loop
    to display the elements in the $a array, type:

        foreach ($element in $a) {$element}

    The Foreach loop iterates through the array and returns each value in
    the array until reaching the end of the array.

    The For loop is useful when you are incrementing counters while examining
    the elements in an array. For example, to return every other value in an
    array by using a For loop, type:

        for ($i = 0; $i -le ($a.length - 1); $i += 2) {$a[$i]}

    You can use a While loop to display the elements in an array until a
    defined condition is no longer true. For example, to display the elements
    in the $a array while the array index is less than 4, type:

        $i=0
        while($i -lt 4) {$a[$i]; $i++}

    To learn about the properties and methods of an array, such as the Length
    property and the SetValue method, use the InputObject parameter of the
    Get-Member cmdlet. When you pipe an array to Get-Member, it displays
    information about the objects in the array. When you use the InputObject
    parameter, it displays information about the array.

    To find the properties and methods of the $a array, type:

    get-member -inputobject $a

  MANIPULATING AN ARRAY
    You can change the elements in an array, add an element to an array, and
    combine the values from two arrays into a third array.

    To change the value of a particular element in an array, specify the
    array name and the index of the element that you want to change, and then
    use the assignment operator (=) to specify a new value for the element. For
    example, to change the value of the second item in the $a array (index
    position 1) to 10, type:

        $a[1] = 10

    You can also use the SetValue method of an array to change a value. The
    following example changes the second value (index position 1) of the $a
    array to 500:

        $a.SetValue(500,1)

    You can append an element to an existing array by using the += operator.
    This operator adds to an existing value. When the operator is used on an
    element of an array, it increases the value of the element. When the
    operator is used on the array itself, it appends the value. For example,
    to append an element with a value of 200 to the $a array, type:

        $a += 200

    It is not easy to delete elements from an array, but you can create a new
    array that contains only selected elements of an existing array. For
    example, to create the $t array with all the elements in the $a array
    except for the value at index position 2, type:

        $t = $a[0,1 + 3..($a.length - 1)]

    To combine two arrays into a single array, use the plus operator (+). The
    following example creates two arrays, combines them, and then displays
    the resulting combined array.

        $x = 1,3
        $y = 5,9
        $z = $x + $y

    As a result, the $z array contains 1, 3, 5, and 9.

    To delete an array, use the Remove-Item cmdlet to delete the variable that
    contains the array. The following command specifies the element "a" in the
    Variable: drive.

        remove-item variable:a

    (For more information about the Variable: drive, see the Variable provider
    Help topic.)

SEE ALSO
    about_Assignment_Operators
    about_Hash_Tables
    about_Operators
    about_For
    about_Foreach
    about_While


about_Assignment_Operators

TOPIC
    about_assignment_operators

SHORT DESCRIPTION
    Describes how to use operators to assign values to variables.

LONG DESCRIPTION
    Assignment operators assign one or more values to a variable. They can
    perform numeric operations on the values before the assignment.

    Windows PowerShell supports the following assignment operators.

    Operator  Description
    -------   -----------
    =         Sets the value of a variable to the specified value.

    +=        Increases the value of a variable by the specified value, or
              appends the specified value to the existing value.

    -=        Decreases the value of a variable by the specified value.

    *=        Multiplies the value of a variable by the specified value, or
              appends the specified value to the existing value.

    /=        Divides the value of a variable by the specified value.

    %=        Divides the value of a variable by the specified value and
              then assigns the remainder (modulus) to the variable.

    ++        Increases the value of a variable, assignable property, or
              array element by 1.

    --        Decreases the value of a variable, assignable property, or
              array element by 1.

  SYNTAX
    The syntax of the assignment operators is as follows:

        <assignable-expression> <assignment-operator> <value>

    Assignable expressions include variables and properties.  The value can be
    a single value, an array of values, or a command, expression, or statement.

    The increment and decrement operators are unary operators. Each has prefix
    and postfix versions.

        <assignable-expression><operator>
        <operator><assignable-expression>

    The assignable expression must a number or it must be convertible to a
    number.

  ASSIGNING VALUES
    Variables are named memory spaces that store values. You store the values
    in variables by using the assignment operator (=). The new value can
    replace the existing value of the variable, or you can append a new value
    to the existing value.

    The basic assignment operator is the equal sign (=)(ASCII 61). For example,
    the following statement assigns the value Windows PowerShell to the
    $MyShell variable:

        $MyShell = "Windows PowerShell"

    When you assign a value to a variable in Windows PowerShell, the variable
    is created if it did not already exist. For example, the first of the
    following two assignement statements creates the $a variable and assigns
    a value of 6 to $a. The second assignment statement assigns a value
    of 12 to $a. The first statement creates a new variable. The second
    statement changes only its value:

        $a = 6
        $a = 12

    Variables in Windows PowerShell do not have a specific data type unless you
    cast them. When a variable contains only one object, the variable takes the
    data type of that object. When a variable contains a collection of objects,
    the variable has the System.Object data type. Therefore, you can assign any
    type of object to the collection. The following example shows that you can
    add process objects, service objects, strings, and integers to a variable
    without generating an error:

        $a = get-process
        $a += get-service
        $a += "string"
        $a += 12

    Because the assignment operator (=) has a lower precedence than the
    pipeline operator (|), parentheses are not required to assign the result
    of a command pipeline to a variable. For example, the following command
    sorts the services on the computer and then assigns the sorted services
    to the $a variable:

        $a = get-service | sort name

    You can also assign the value created by a statement to a variable, as in
    the following example:

        $a = if ($b -lt 0) { 0 } else { $b }

    This example assigns 0 to the $a variable if the value of $b is less
    than 0. It assigns the value of $b to $a if the value of $b is not less
    than zero.

  THE ASSIGNMENT OPERATOR (=)
    The assignment operator (=) assigns values to variables. If the variable
    already has a value, the assignment operator (=) replaces the value
    without warning.

    The following statement assigns the integer value 6 to the $a variable:

        $a = 6

    To assign a string value to a variable, enclose the string value in
    quotation marks, as follows:

        $a = "baseball"

    To assign an array (multiple values) to a variable, separate the values
    with commas, as follows:

        $a = "apple", "orange", "lemon", "grape"

    To assign a hash table to a variable, use the standard hash table notation
    in Windows PowerShell. Type an at sign (@) followed by key/value pairs that
    are separated by semicolons (;) and enclosed in braces ({ }). For example,
    to assign a hash table to the $a variable, type:

        $a = @{one=1; two=2; three=3}

    To assign hexadecimal values to a variable, precede the value with "0x".
    Windows PowerShell converts the hexadecimal value (0x10) to a decimal
    value (in this case, 16) and assigns that value to the $a variable. For
    example, to assign a value of 0x10 to the $a variable, type:

        $a = 0x10

    To assign an exponential value to a variable, type the root number, the
    letter "e", and a number that represents a multiple of 10. For example, to
    assign a value of 3.1415 to the power of 1,000 to the $a variable, type:

        $a = 3.1415e3

    Windows PowerShell can also convert kilobytes (KB), megabytes (MB), and
    gigabytes (GB) into bytes. For example, to assign a value of 10 kilobytes
    to the $a variable, type:

        $a = 10kb

  THE ASSIGNMENT BY ADDITION OPERATOR (+=)
    The assignment by addition operator (+=) either increments the value of a
    variable or appends the specified value to the existing value. The action
    depends on whether the variable has a numeric or string type and whether
    the variable contains a single value (a scalar) or multiple values
    (a collection).

    The += operator combines two operations. First, it adds, and then it
    assigns. Therefore, the following statements are equivalent:

        $a += 2
        $a = ($a + 2)

    When the variable contains a single numeric value, the += operator
    increments the existing value by the amount on the right side of the
    operator. Then, the operator assigns the resulting value to the variable.
    The following example shows how to use the += operator to increase the
    value of a variable:

        C:\PS> $a = 4
        C:\PS> $a += 2
        C:\PS> $a
        6

    When the value of the variable is a string, the value on the right side of
    the operator is appended to the string, as follows:

        C:\PS> $a = "Windows"
        C:\PS> $a +- " PowerShell"
        C:\PS> $a
        Windows PowerShell

    When the value of the variable is an array, the += operator appends the
    values on the right side of the operator to the array. Unless the array is
    explicitly typed by casting, you can append any type of value to the array,
    as follows:

        C:\PS> $a = 1,2,3
        C:\PS> $a += 2
        C:\PS> $a
        1
        2
        3
        2
        C:\PS> $a += "String"
        C:\PS> $a
        1
        2
        3
        2
        String

    When the value of a variable is a hash table, the += operator appends the
    value on the right side of the operator to the hash table. However, because
    the only type that you can add to a hash table is another hash table, all
    other assignments fail.

    For example, the following command assigns a hash table to the $a variable.
    Then, it uses the += operator to append another hash table to the existing
    hash table, effectively adding a new key/value pair to the existing hash
    table. This command succeeds, as shown in the output:

        C:\PS> $a = @{a = 1; b = 2; c = 3}
        C:\PS> $a += @{mode = "write"}
        C:\PS> $a
        Name                           Value
        ----                           -----
        a                              1
        b                              2
        mode                           write
        c                              3

    The following command attempts to append an integer (1) to the hash table
    in the $a variable. This command fails:

        C:\PS> $a = @{a = 1; b = 2; c = 3}
        C:\PS> $a += 1
        You can add another hash table only to a hash table.
        At line:1 char:6
        + $a += <<<<  1

  THE ASSIGNMENT BY SUBTRACTION OPERATOR (-=)
    The assignment by subtraction operator (-=) decrements the value of a
    variable by the value that is specified on the right side of the operator.
    This operator cannot be used with string variables, and it cannot be used
    to remove an element from a collection.

    The -= operator combines two operations. First, it subtracts, and then it
    assigns. Therefore, the following statements are equivalent:

        $a -= 2
        $a = ($a - 2)

    The following example shows how to use of the -= operator to decrease the
    value of a variable:

        C:\PS> $a = 8
        C:\PS> $a -= 2
        C:\PS> $a
        6

    You can also use the -= assignment operator to decrease the value of a
    member of a numeric array. To do this, specify the index of the array
    element that you want to change. In the following example, the value of the
    third element of an array (element 2) is decreased by 1:

        C:\PS> $a = 1,2,3
        C:\PS> $a[2] -= 1.
        C:\PS> $a
        1
        2
        2

    You cannot use the -= operator to delete the values of a variable. To
    delete all the values that are assigned to a variable, use the Clear-Item
    or Clear-Variable cmdlets to assign a value of $null or "" to the variable.

        $a = $null

    To delete a particular value from an array, use array notation to assign a
    value of $null to the particular item. For example, the following statement
    deletes the second value (index position 1) from an array:

        C:\PS> $a = 1,2,3
        C:\PS> $a
        1
        2
        3

        C:\PS> $a[1] = $null
        C:\PS> $a
        1
        3

    To delete a variable, use the Remove-Variable cmdlet. This method is useful
    when the variable is explicitly cast to a particular data type, and you
    want an untyped variable. The following command deletes the $a variable:

        remove-variable a

  THE ASSIGNMENT BY MULTIPLICATION OPERATOR (*=)
    The assignment by multiplication operator (*=) multiplies a numeric value
    or appends the specified number of copies of the string value of a
    variable.

    When a variable contains a single numeric value, that value is multiplied
    by the value on the right side of the operator. For example, the following
    example shows how to use the *= operator to multiply the value of a
    variable:

        C:\PS> $a = 3
        C:\PS> $a *= 4
        C:\PS> $a
        12

    In this case, the *= operator combines two operations. First, it
    multiplies, and then it assigns. Therefore, the following statements are
    equivalent:

        $a *= 2
        $a = ($a * 2)

    When a variable contains a string value, Windows PowerShell appends the
    specified number of strings to the value, as follows:

        C:\PS> $a = "file"
        C:\PS> $a *= 4
        C:\PS> $a
        filefilefilefile

    To multiply an element of an array, use an index to identify the element
    that you want to multiply. For example, the following command multiplies
    the first element in the array (index position 0) by 2:

        $a[0] *= 2

  THE ASSIGNMENT BY DIVISION OPERATOR (/=)
    The assignment by division operator (/=) divides a numeric value by the
    value that is specified on the right side of the operator. The operator
    cannot be used with string variables.

    The /= operator combines two operations. First, it divides, and then it
    assigns. Therefore, the following two statements are equivalent:

        $a /= 2
        $a = ($a / 2)

    For example, the following command uses the /= operator to divide the value
    of a variable:

        C:\PS> $a = 8
        C:\PS> $a /=2
        C:\PS> $a
        4

    To divide an element of an array, use an index to identify the element that
    you want to change. For example, the following command divides the second
    element in the array (index position 1) by 2:

        $a[1] /= 2

  THE  ASSIGNMENT BY MODULUS OPERATOR (%=)
    The assignment by modulus operator (%=) divides the value of a variable by
    the value on the right side of the operator. Then, the %= operator assigns
    the remainder (known as the modulus) to the variable. You can use this
    operator only when a variable contains a single numeric value. You cannot
    use this operator when a variable contains a string variable or an array.

    The %= operator combines two operations. First, it divides and determines
    the remainder, and then it assigns the remainder to the variable.
    Therefore, the following statements are equivalent:

        $a %= 2
        $a = ($a % 2)

    The following example shows how to use the %= operator to save the modulus
    of a quotient:

        C:\PS> $a = 7
        C:\PS> $a %= 4
        C:\PS> $a
        3

  THE INCREMENT AND DECREMENT OPERATORS

    The increment operator (++) increases the value of a variable by 1. When
    you use the increment operator in a simple statement, no value is returned.
    To view the result, display the value of the variable, as follows:

        C:\PS> $a = 7
        C:\PS> ++$a
        C:\PS> $a
        8

    To force a value to be returned, enclose the variable and the operator in
    parentheses, as follows:

        C:\PS> $a = 7
        C:\PS> (++$a)
        8

    The increment operator can be placed before (prefix) or after (postfix) a
    variable. The prefix version of the operator increments a variable before
    its value is used in the statement, as follows:

        C:\PS> $a = 7
        C:\PS> $c = ++$a
        C:\PS> $a
        8
        C:\PS> $c
        8

    The postfix version of the operator increments a variable after its value
    is used in the statement. In the following example, the $c and $a variables
    have different values because the value is assigned to $c before $a
    changes:

        C:\PS> $a = 7
        C:\PS> $c = $a++
        C:\PS> $a
        8
        C:\PS> $c
        7

    The decrement operator (--) decreases the value of a variable by 1. As with
    the increment operator, no value is returned when you use the operator in a
    simple statement. Use parentheses to return a value, as follows:

        C:\PS> $a = 7
        C:\PS> --$a
        C:\PS> $a
        6
        C:\PS> (--$a)
        5

    The prefix version of the operator decrements a variable before its value
    is used in the statement, as follows:

        C:\PS> $a = 7
        C:\PS> $c = --$a
        C:\PS> $a
        6
        C:\PS> $c
        6

    The postfix version of the operator decrements a variable after its value
    is used in the statement. In the following example, the $d and $a variables
    have different values because the value is assigned to $d before $a
    changes:

        C:\PS> $a = 7
        C:\PS> $d = $a--
        C:\PS> $a
        6
        C:\PS> $d
        7

  MICROSOFT .NET FRAMEWORK TYPES
    By default, when a variable has only one value, the value that is assigned
    to the variable determines the data type of the variable. For example, the
    following command creates a variable that has the Integer (System.Int32)
    type:

        $a = 6

    To find the .NET Framework type of a variable, use the GetType method and
    its FullName property, as follows. Be sure to include the parentheses after
    the GetType method name, even though the method call has no arguments:

        C:\PS> $a = 6
        C:\PS> $a.gettype().fullname
        System.Int32

    To create a variable that contains a string, assign a string value to the
    variable. To indicate that the value is a string, enclose it in quotation
    marks, as follows:

        C:\PS> $a = "6"
        C:\PS> $a.gettype().fullname
        System.String

    If the first value that is assigned to the variable is a string, Windows
    PowerShell treats all operations as string operations and casts new values
    to strings. This occurs in the following example:

        C:\PS> $a = "file"
        C:\PS> $a += 3
        C:\PS> $a
        file3

    If the first value is an integer, Windows PowerShell treats all operations
    as integer operations and casts new values to integers. This occurs in the
    following example:

        C:\PS> $a = 6
        C:\PS> $a += "3"
        C:\PS> $a
        9

    You can cast a new scalar variable as any .NET Framework type by placing
    the type name in brackets that precede either the variable name or
    the first assignment value. When you cast a variable, you can determine the
    types of data that can be stored in the variable. And, you can determine
    how the variable behaves when you manipulate it.

    For example, the following command casts the variable as a string type:

        C:\PS> [string]$a = 27
        C:\PS> $a += 3
        C:\PS> $a
        273

    The following example casts the first value, instead of casting the
    variable:

        $a = [string]27

    When you cast a variable to a specific type, the common convention is to
    cast the variable, not the value. However, you cannot recast the data type
    of an existing variable if its value cannot be converted to the new data
    type. To change the data type, you must replace its value, as follows:

        C:\PS> $a = "string"
        C:\PS> [int]$a
        Cannot convert value "string" to type "System.Int32". Error: "Input
        string was not in a correct format."
        At line:1 char:8
        + [int]$a <<<<

        C:\PS> [int]$a =3

    In addition, when you precede a variable name with a data type, the type
    of that variable is locked unless you explicitly override the type by
    specifying another data type. If you try to assign a value that is
    incompatible with the existing type, and you do not explicitly override the
    type, Windows PowerShell displays an error, as shown in the following
    example:

        C:\PS> $a = 3
        C:\PS> $a = "string"

        C:\PS> [int]$a = 3
        C:\PS> $a = "string"
        Cannot convert value "string" to type "System.Int32". Error: "Input
        string was not in a correct format."
        At line:1 char:3
        + $a <<<<  = "string"

        C:\PS> [string]$a = "string"

    In Windows PowerShell, the data types of variables that contain multiple
    items in an array are handled differently from the data types of variables
    that contain a single item. Unless a data type is specifically assigned to
    an array variable, the data type is always System.Object []. This data type
    is specific to arrays.

    Sometimes, you can override the default type by specifying another
    type. For example, the following command casts the variable as a string []
    array type:

        [string []] $a = "one", "two", "three"

    Windows PowerShell variables can be any .NET Framework data type. In
    addition, you can assign any fully qualified .NET Framework data type that
    is available in the current process. For example, the following command
    specifies a System.DateTime data type:

        [system.datetime]$a = "5/31/2005"

    The variable will be assigned a value that conforms to the System.DateTime
    data type. The value of the $a variable would be the following:

        Tuesday, May 31, 2005 12:00:00 AM

  ASSIGNING MULTIPLE VARIABLES
    In Windows PowerShell, you can assign values to multiple variables by using
    a single command. The first element of the assignment value is assigned to
    the first variable, the second element is assigned to the second variable,
    the third element to the third variable, and so on. For example, the
    following command assigns the value 1 to the $a variable, the value 2 to
    the $b variable, and the value 3 to the $c variable:

        C:\PS> $a, $b, $c = 1, 2, 3

    If the assignment value contains more elements than variables, all the
    remaining values are assigned to the last variable. For example, the
    following command contains three variables and five values:

        $a, $b, $c = 1, 2, 3, 4, 5

    Therefore, Windows PowerShell assigns the value 1 to the $a variable and
    the value 2 to the $b variable. It assigns the values 3, 4, and 5 to
    the $c variable. To assign the values in the $c variable to three other
    variables, use the following format:

        $d, $e, $f = $c

    This command assigns the value 3 to the $d variable, the value 4 to
    the $e variable, and the value 5 to the $f variable.

    You can also assign a single value to multiple variables by chaining the
    variables. For example, the following command assigns a value of "three"
    to all four variables:

        $a = $b = $c = $d = "three"

  VARIABLE-RELATED CMDLETS
    In addition to using an assignment operation to set a variable value, you
    can also use the Set-Variable cmdlet. For example, the following command
    uses Set-Variable to assign an array of 1, 2, 3 to the $a variable.

        Set-Variable -name a -value 1, 2, 3

SEE ALSO
    about_Arrays
    about_Hash_Tables
    about_Variables
    Clear-Variable
    Remove-Variable
    Set-Variable


about_Automatic_Variables

TOPIC
    about_Automatic_Variables

SHORT DESCRIPTION
    Describes variables that store state information for Windows PowerShell.
    These variables are created and maintained by Windows PowerShell.

LONG DESCRIPTION
    Here is a list of the automatic variables in Windows PowerShell:

    $$
       Contains the last token in the last line received by the session.

    $?
       Contains the execution status of the last operation. It contains
    TRUE if the last operation succeeded and FALSE if it failed.

    $^
       Contains the first token in the last line received by the session.

    $_
       Contains the current object in the pipeline object. You can use this
       variable in commands that perform an action on every object or on
       selected objects in a pipeline.

    $Args
       Contains an array of the undeclared parameters and/or parameter
       values that are passed to a function, script, or script block.
       When you create a function, you can declare the parameters by using the
       param keyword or by adding a comma-separated list of parameters in
       parentheses after the function name.

    $ConsoleFileName
       Contains the path of the console file (.psc1) that was most
       recently used in the session. This variable is populated when
       you start Windows PowerShell with the PSConsoleFile parameter or
       when you use the Export-Console cmdlet to export snap-in names to a
       console file.

       When you use the Export-Console cmdlet without parameters, it
       automatically updates the console file that was most recently
       used in the session. You can use this automatic variable to determine
       which file will be updated.

    $Error
       Contains an array of error objects that represent the most
       recent errors. The most recent error is the first error object in the
       array ($Error[0]).

    $Event
        Contains a PSEventArgs object that represents the event that is being
        processed.  This variable is populated only within the Action block of
        an event registration command, such as Register-ObjectEvent. The value
        of this variable is the same object that the Get-Event cmdlet returns.
        Therefore, you can use the properties of the $Event variable, such as
        $Event.TimeGenerated , in an Action script block.

    $EventSubscriber
        Contains a PSEventSubscriber object that represents the event subscriber
        of the event that is being processed. This variable is populated only
        within the Action block of an event registration command. The value of
        this variable is the same object that the Get-EventSubscriber cmdlet
        returns.

    $ExecutionContext
       Contains an EngineIntrinsics object that represents the
       execution context of the Windows PowerShell host. You can
       use this variable to find the execution objects that are
       available to cmdlets.

    $False
       Contains FALSE. You can use this variable to represent
       FALSE in commands and scripts instead of using the string "false".
       The string can be interpreted as TRUE if it is converted to a non-empty
       string or to a non-zero integer.

    $ForEach
       Contains the enumerator of a ForEach-Object loop. You can use the
       properties and methods of enumerators on the value of the $ForEach
       variable. This variable exists only while the For loop is running. It
       is deleted when the loop is completed.

    $Home
       Contains the full path of the user's home directory. This variable is
       the equivalent of the %homedrive%%homepath% environment variables,
       typically C:\Documents and Settings\<user>.

    $Host
       Contains an object that represents the current host application
       for Windows PowerShell. You can use this variable to represent the
       current host in commands or to display or change the properties of
       the host, such as $Host.version or $Host.CurrentCulture, or
       $host.ui.rawui.setbackgroundcolor("Red").

    $Input
       An enumerator that contains the input that is passed to a function. The
       $Input variable is case-sensitive and is available only in functions and
       in script blocks. (Script blocks are essentially unnamed functions.)
       In the Process block of a function, the $Input variable contains the
       object that is currently in the pipeline. When the Process block is
       completed, the value of $Input is NULL. If the function does not have a
       Process block, the value of $Input is available to the End block, and it
       contains all the input to the function.

    $LastExitCode
       Contains the exit code of the last Windows-based program that was run.

    $Matches
       The $Matches variable works with the -match and -not match operators.
       When you submit scalar input to the -match or -notmatch operator, and
       either one detects a match, they return a Boolean value and populate
       the $Matches automatic variable with a hash table of any string values
       that were matched. For more information about the -match operator, see
       about_comparison_operators.

    $MyInvocation
       Contains an object with information about the current command, such as
       a script, function, or script block. You can use the information in the
       object, such as the path and file name of the script
       ($myinvocation.mycommand.path) or the name of a function
       ($myinvocation.mycommand.name) to identify the current command. This is
       particularly useful for finding the name of the script that is running.

    $NestedPromptLevel
       Contains the current prompt level. A value of 0 indicates the original
       prompt level. The value is incremented when you enter a nested level and
       decremented when you exit it.

       For example, Windows PowerShell presents a nested command prompt when
       you use the $Host.EnterNestedPrompt method. Windows PowerShell also
       presents a nested command prompt when you reach a breakpoint in the
       Windows PowerShell debugger.

       When you enter a nested prompt, Windows PowerShell pauses the current
       command, saves the execution context, and increments the value of
       the $NestedPromptLevel variable. To create additional nested command
       prompts (up to 128 levels) or to return to the original command prompt,
       complete the command, or type "exit".

       The $NestedPromptLevel variable helps you track the prompt level. You
       can create an alternative Windows PowerShell command prompt that
       includes this value so that it is always visible.

    $NULL
       Contains a NULL or empty value. You can use this variable to
       represent NULL in commands and scripts instead of using the string
       "NULL". The string can be interpreted as TRUE if it is converted to a
       non-empty string or a non-zero integer.

    $PID
       Contains the process identifier (PID) of the process that is hosting
       the current Windows PowerShell session.

    $Profile
       Contains the full path of the Windows PowerShell profile for the
       current user and the current host application. You can use this variable
       to represent the profile in commands. For example, you can use it in
       a command to determine whether a profile has been created:

           test-path $profile

       Or, you can use it in a command to create a profile:

           new-item -type file -path $pshome -force

       You can also use it in a command to open the profile in Notepad:

           notepad $profile

    $PSBoundParameters
       Contains a dictionary of the active parameters and their current
       values. This variable has a value only in a scope where parameters
       are declared, such as a script or function. You can use it to
       display or change the current values of parameters or to pass
       parameter values to another script or function.

       For example:

         function test {
            param($a, $b)

            # Display the parameters in dictionary format.
            $psboundparameters

            # Call the Test1 function with $a and $b.
            test1 @psboundparameters
         }

    $PsCmdlet
       Contains an object that represents the cmdlet or advanced function
       that is being run.

       You can use the properties and methods of the object in your cmdlet
       or function code to respond to the conditions of use. For example,
       the ParameterSetName property contains the name of the parameter set
       that is being used, and the ShouldProcess method adds the WhatIf and
       Confirm parameters to the cmdlet dynamically.

       For more information about the $PSCmdlet automatic variable, see
       about_Functions_Advanced.

    $PsCulture
       Contains the name of the culture currently in use in the operating
       system. The culture determines the display format of items such
       as numbers, currrency, and dates. This is the value of the
       System.Globalization.CultureInfo.CurrentCulture.Name property of the
       system. To get the System.Globalization.CultureInfo object for the
       system, use the Get-Culture cmdlet.

    $PSDebugContext
       While debugging, this variable contains information about the
       debugging environment. Otherwise, it contains a NULL value.
       As a result, you can use it to indicate whether the debugger has
       control. When populated, it contains a PsDebugContext object that has
       Breakpoints and InvocationInfo properties. The InvocationInfo property
       has several useful properties, including the Location property. The
       Location property indicates the path of the script that is being
       debugged.

    $PsHome
       Contains the full path of the installation directory for Windows
       PowerShell, typically, %windir%\System32\WindowsPowerShell\v1.0. You
       can use this variable in the paths of Windows PowerShell files. For
       example, the following command searches the conceptual Help topics for
       the word "variable":

            select-string -pattern variable -path $pshome\*.txt

    $PSScriptRoot
       Contains the directory from which the script module is being executed.
       This variable allows scripts to use the module path to access other
       resources.

    $PsUICulture
       Contains the name of the user interface (UI) culture that is currently
       in use in the operating system. The UI culture determines which text
       strings are used for user interface elements, such as menus and
       messages. This is the value of the
       System.Globalization.CultureInfo.CurrentUICulture.Name property of the
       system. To get the System.Globalization.CultureInfo object for the
       system, use the Get-UICulture cmdlet.

    $PsVersionTable
        Contains a read-only hash table that displays details about the
        version of Windows PowerShell that is running in the current session.
        The table includes the following items:

        CLRVersion:            The version of the common language runtime (CLR)

        BuildVersion:          The build number of the current version

            PSVersion:             The Windows PowerShell version number

            WSManStackVersion:     The version number of the WS-Management stack

        PSCompatibleVersions:  Versions of Windows PowerShell that are
                                   compatible with the current version

            SerializationVersion   The version of the serialization method

            PSRemotingProtocolVersion
                                   The version of the Windows PowerShell remote
                                   management protocol

    $Pwd
       Contains a path object that represents the full path of the current
       directory.

    $Sender
        Contains the object that generated this event. This variable is
        populated only within the Action block of an event registration command.
        The value of this variable can also be found in the Sender property of
        the PSEventArgs (System.Management.Automation.PSEventArgs) object that
        Get-Event returns.

    $ShellID
       Contains the identifier of the current shell.

    $SourceArgs
        Contains objects that represent the event arguments of the event that
        is being processed. This variable is populated only within the Action
        block of an event registration command.  The value of this variable
        can also be found in the SourceArgs property of the PSEventArgs
        (System.Management.Automation.PSEventArgs) object that Get-Event
        returns.

    $SourceEventArgs
        Contains an object that represents the first event argument that derives
        from EventArgs of the event that is being processed. This variable is
        populated only within the Action block of an event registration command.
        The value of this variable can also be found in the SourceArgs property
        of the PSEventArgs (System.Management.Automation.PSEventArgs) object
        that Get-Event returns.

    $This
        In a script block that defines a script property or script method, the
        $This variable refers to the object that is being extended.

    $True
       Contains TRUE. You can use this variable to represent
       TRUE in commands and scripts.

SEE ALSO
    about_Hash_Tables
    about_Preference_Variables
    about_Variables


about_Break

TOPIC
    about_Break

SHORT DESCRIPTION
    Describes a statement you can use to immediately exit Foreach, For, While,
    Do, or Switch statements.

LONG DESCRIPTION
    When a Break statement appears in a loop, such as a Foreach, For, Switch,
    or While loop, the Break statement causes Windows PowerShell to immediately
    exit the loop. In a Switch construct that does not loop, Break causes
    Windows PowerShell to exit the Switch code block.

    A Break statement can include a label that lets you exit embedded loops.
    A label can specify any loop keyword, such as Foreach, For, or While, in a
    script. When you use a label, Break exits the specified loop. Break exits
    the specified loop, regardless of which loop the Break statement is in.

    The following example shows how to use a Break statement to exit a For
    statement:

        for($i=1; $i -le 10; $i++)
        {
            Write-Host $i
            break
        }

    In this example, the Break statement exits the For loop when the $i
    variable equals 1. Even though the For statement evaluates to True
    until $i is greater than 10, Windows PowerShell reaches the break statement
    the first time the For loop is run.

    It is more common to use the Break statement in a loop where
    an inner condition must be met. Consider the following Foreach
    statement example:

        $i=0
        $varB = 10,20,30,40
        foreach ($val in $varB)
        {
            $i++
            if ($val -eq 30)
            {
                break
            }
        }
        Write-Host "30 was found in array position $i"

    In this example, the Foreach statement iterates the $varB array. Each
    time the code block is run, the $i variable is incremented by 1. The
    If statement evaluates to False the first two times the
    loop is run. The third time the loop is run, $i equals 3, and the $val
    variable equals 30. At this point, the Break statement runs, and the
    Foreach loop exits.

    You break out of the other looping statements in the same way you
    break out of the Foreach loop. In the following example, the Break
    statement exits a While statement when a DivideByZeroException exception
    is trapped using the Trap statement.

        $i = 3
        while ($true)
        {
            trap [DivideByZeroException]
            {
                Write-Host "divide by zero trapped"
                break
            }
            1 / $i--
        }

    A Break statement can include a label. If you use the Break keyword with
    a label, Windows PowerShell exits the labeled loop instead of exiting the
    current loop. The syntax for a label is as follows (this example shows a
    label in a While loop):

        :myLabel while (<condition>) { <statement list>}

    The label is a colon followed by a name that you assign. The label must be
    the first token in a statement, and it must be followed by the looping
    keyword, such as While.

    In Windows PowerShell, only loop keywords, such as Foreach, For, and While
    can have a label.

    Break moves execution out of the labeled loop. In embedded loops, this has
    a different result than the Break keyword has when it is used by itself.
    This schematic example has a While statement with a For statement:

        :myLabel while (<condition 1>)
        {
            for ($item in $items)
            {
                if (<condition 2>) { break myLabel }
                $item = $x   # A statement inside the For-loop
            }
        }
        $a = $c  # A statement after the labeled While-loop

    If condition 2 evaluates to True, the execution of the script skips down
    to the statement after the labeled loop. In the example, execution starts
    again with the statement "$a = $c".

    You can nest many labeled loops, as shown in the following schematic
    example.

        :red while (<condition1>)
        {
            :yellow while (<condition2>)
            {
                while (<condition3>)
                {
                    if ($a) {break}
                    if ($b) {break red}
                    if ($c) {break yellow}
                }
                # After innermost loop
            }
                # After "yellow" loop
        }
                # After "red" loop

    If the $b variable evaluates to True, execution of the script resumes
    after the loop that is labeled "red". If the $c variable evaluates to
    True, execution of the script control resumes after the loop that is
    labeled "yellow".

    If the $a variable evaluates to True, execution resumes after the innermost
    loop. No label is needed.

    Windows PowerShell does not limit how far labels can resume execution. The
    label can even pass control across script and function call boundaries.

    The Break keyword is used to leave the Switch construct. For example,
    the following Switch statement uses Break statements to test for the
    most specific condition:

        $var = "word2"
        switch -regex ($var)
        {
            "word2"
            {
                Write-Host "Exact" $_
                break
            }

            "word.*"
            {
                Write-Host "Match on the prefix" $_
                break
            }

            "w.*"
            {
                Write-Host "Match on at least the first letter" $_
                break
            }

            default
            {
                Write-Host "No match" $_
                break
            }
        }

    In this example, the $var variable is created and initialized to a string
    value of "word2". The Switch statement uses the Regex class to match the
    variable value first with the term "word2". (The Regex class is a regular
    expression Microsoft .NET Framework class.) Because the variable value and
    the first test in the Switch statement match, the first code block in the
    Switch statement runs.

    When Windows PowerShell reaches the first Break statement, the Switch
    statement exits. If the four Break statements are removed from the example,
    all four conditions are met. This example uses the break statement to
    display results when the most specific condition is met.

SEE ALSO
    about_Comparison_Operators
    about_For
    about_Foreach
    about_Switch
    about_While


about_Command_Precedence

TOPIC
    about_Command_Precedence

SHORT DESCRIPTION
    Describes how Windows PowerShell determines which command to run.

LONG DESCRIPTION
    This topic explains how Windows PowerShell determines which command to
    run, especially when a session contains more than one command with the
    same name. It also explains how to run commands that do not run by
    default, and it explains how to avoid command-name conflicts in your
    session.

  COMMAND PRECEDENCE
      When a session includes commands that have the same name, Windows
      PowerShell uses the following rules to decide which command to run.

      These rules become very important when you add commands to your session
      from modules, snap-ins, and other sessions.

      -- If you specify the path to a command, Windows PowerShell runs the
         command at the location specified by the path.

         For example, the following command runs the FindDocs.ps1
         script in the C:\TechDocs directory:

             C:\TechDocs\FindDocs.ps1

         As a security feature, Windows PowerShell does not run executable
         (native) commands, including Windows PowerShell scripts, unless the
         command is located in a path that is listed in the Path environment
         variable ($env:path) or unless you specify the path to the script
         file.

         To run a script that is in the current directory, specify the full
         path, or type a dot (.) to represent the current directory.

         For example, to run the FindDocs.ps1 file in the current directory,
         type:

             .\FindDocs.ps1

      -- If you do not specify a path, Windows PowerShell uses the following
         precedence order when it runs commands:

              1. Alias
              2. Function
              3. Cmdlet
              4. Native Windows commands

          Therefore, if you type "help", Windows PowerShell first looks for an
          alias named "help", then a function named "Help", and finally a
          cmdlet named "Help". It runs the first "help" item that it finds.

          For example, assume you have a function named Get-Map. Then, you add
          or import a cmdlet named Get-Map. By default, Windows PowerShell
          runs the function when you type "Get-Map".

      -- When the session contains items of the same type that have the same
         name, such as two cmdlets with the same name, Windows PowerShell
         runs the item that was added to the session most recently.

         For example, assume you have a cmdlet named Get-Date. Then, you import
         another cmdlet named Get-Date. By default, Windows PowerShell runs
         the most-recently imported cmdlet when you type "Get-Date".

  HIDDEN and REPLACED ITEMS
      As a result of these rules, items can be replaced or hidden by items with
      the same name.

      --  Items are "hidden" or "shadowed" if you can still access the original
          item, such as by qualifying the item name with a module or snap-in
          name.

          For example, if you import a function that has the same name as a
          cmdlet in the session, the cmdlet is hidden (but not replaced)
          because it was imported from a snap-in or module.

      --  Items are "replaced" or "overwritten" if you can no longer access
          the original item.

          For example, if you import a variable that has the same name as a
          a variable in the session, the original variable is replaced and is
          no longer accessible. You cannot qualify a variable with a module
          name.

          Also, if you type a function at the command line and then import
          a function with the same name, the original function is replaced and
          is no longer accessible.

  RUNNING HIDDEN COMMANDS
      You can run particular commands by specifying item properties that
      distinguish the command from other commands that might have the same
      name.

      You can use this method to run any command, but it is especially useful
      for running hidden commands.

      Use this method as a best practice when writing scripts that you intend
      to distribute because you cannot predict which commands might be present
      in the session in which the script runs.

      QUALIFIED NAMES
      You can run commands that have been imported from a Windows PowerShell
      snap-in or module or from another session by qualifying the command
      name with the name of the module or snap-in in which it originated.

      You can qualify commands, but you cannot qualify variables or aliases.

      For example, if the Get-Date cmdlet from the Microsoft.PowerShell.Utility
      snap-in is hidden by an alias, function, or cmdlet with the same name, you
      can run it by using the snap-in-qualified name of the cmdlet:

          Microsoft.PowerShell.Utility\Get-Date

      To run a New-Map command that was added by the MapFunctions module, use
      its module-qualified name:

          MapFunctions\New-Map

      To find the snap-in or module from which a command was imported, use the
      following Get-Command command format:

          get-command <command-name> | format-list -property Name, PSSnapin, Module

      For example, to find the source of the Get-Date cmdlet, type:

          get-command get-date | format-list -property Name, PSSnapin, Module

          Name     : Get-Date
          PSSnapIn : Microsoft.PowerShell.Utility
          Module   :

      CALL OPERATOR
      You can also use the Call operator (&) to run any command that you
      can get by using a Get-ChildItem (the alias is "dir"), Get-Command, or
      Get-Module command.

      To run a command, enclose the Get-Command command in parentheses,
      and use the Call operator (&) to run the command.

          &(get-command ...)

      - or -

          &(dir ... )

      For example, if you have a function named Map that is hidden by an
      alias named Map, use the following command to run the function.

          &(get-command -name map -type function)

      - or -

          &(dir function:\map)

      You can also save your hidden command in a variable to make it
      easier to run.

      For example, the following command saves the Map function in the
      $myMap variable and then uses the Call operator to run it.

          $myMap = (get-command -name map -type function)

          &($myMap)

      If a command originated in a module, you can use the following
      format to run it.

         & <PSModuleInfo-object> <command>

      For example, to run the Add-File cmdlet in the FileCommands
      module, use the following command sequence.

         $FileCommands = get-module -name FileCommands

         & $FileCommands Add-File

  REPLACED ITEMS
      Items that have not been imported from a module or snap-in, such as
      functions, variables, and aliases that you create in your session or
      that you add by using a profile can be replaced by commands that have
      the same name. If they are replaced, you cannot access them.

      Variables and aliases are always replaced even if they have been
      imported from a module or snap-in because you cannot use a call operator
      or a qualified name to run them.

      For example, if you type a Get-Map function in your session, and you
      import a function called Get-Map, the original function is replaced.
      You cannot retrieve it in the current session.

  AVOIDING NAME CONFLICTS
      The best way to manage command name conflicts is to prevent them. When
      you name your commands, use a name that is very specific or is likely to
      be unique. For example, add your initials or company name acronym to the
      nouns in your commands.

      Also, when you import commands into your session from a Windows PowerShell
      module or from another session, use the Prefix parameter of the
      Import-Module or Import-PSSession cmdlet to add a prefix to the nouns
      in the names of commands.

      For example, the following command avoids any conflict with the Get-Date
      and Set-Date cmdlets that come with Windows PowerShell when you import
      the DateFunctions module.

          import-module -name DateFunctions -prefix ZZ

      For more information, see Import-Module and Import-PSSession.

SEE ALSO
    about_Path_Syntax
    about_Aliases
    about_Functions
    Alias (provider)
    Function (provider)
    Get-Command
    Import-Module
    Import-PSSession


about_Command_Syntax

TOPIC
    about_Command_Syntax

SHORT DESCRIPTION
    Describes the notation used for Windows PowerShell syntax in Help.

LONG DESCRIPTION
    The Get-Help cmdlet displays the parameter usage for a cmdlet. The Get-Help
    cmdlet uses the following special symbols:

        Angle brackets (<>) indicate placeholder text.
        Brackets ([]) indicate optional items.
        Braces ({}) indicate a choice among values.

    Some cmdlets have more than one set of parameters. Distinct parameter sets
    can share some parameters. The Get-Help cmdlet displays all the parameter
    sets for a cmdlet.

    You can find additional information about a parameter in the parameter
    description and in the parameter attribute table. To view complete
    information about a parameter, use the Full or Parameter parameters of
    Get-Help.

  Syntax
      Windows PowerShell cmdlet Help, Help topics, and other documentation use
      the following notation for cmdlets in syntax descriptions.

          <cmdlet name> -<Required Parameter name> <Required parameter Value>
                       [-<Optional Parameter name> <Optional Parameter Value>]
                       [-<Optional Switch Parameter>]
                       [-<Optional Parameter Name>] <Required parameter Value>

      The following is the syntax for the New-Alias cmdlet.

          New-Alias [-Force] [-PassThru] [-Scope <string>]
              [-Option {None | ReadOnly | Constant | Private | AllScope}]
              [-Description <string>] [-Name] <string> [-Value] <string>
              [-confirm] [-whatif] [<CommonParameters>]

      The syntax is capitalized for readability, but Windows Powershell is
      case-insensitive.

      Parameters appear in order. The order of parameters is significant only
      when the parameter names are optional. If you do not specify parameter
      names when you use a cmdlet, Windows PowerShell assigns values to
      parameters by position and by type.

      Parameter names are preceded by a hyphen (-). Switch parameters appear
      without a value type. Other parameters appear with the Microsoft .NET
      Framework type of the argument required or with an enumeration of
      possible values. For more information about .NET Framework types,
      see http://go.microsoft.com/fwlink/?LinkId=143682.

      Angle brackets (<>) indicate placeholder text. This text can describe the
      type of an item (such as a string or a Process object). It can also be a
      placeholder for one or more common parameters.

      Brackets ([]) indicate optional items. A parameter can be optional, or
      the name of a required parameter can be optional. Switch parameters are
      always optional.

      Braces ({}) appear around the values of an enumeration. In the example of
      the New-Alias cmdlet, the Option parameter can have any of the listed
      values.

  Optional Items
      Brackets ([]) surround optional items. For example, in the New-Alias
      cmdlet syntax description, the Scope parameter is optional. This is
      indicated in the syntax by the brackets around the parameter name
      and type:

          [-Scope <string>]

      Both the following examples are correct uses of the New-Alias cmdlet:

          New-Alias -Name utd -Value Update-TypeData
          New-Alias -Name utd -Value Update-TypeData -Scope global

      A parameter name can be optional even if the value for that parameter is
      required. This is indicated in the syntax by the brackets around the
      parameter name but not the parameter type, as in this example from the
      New-Alias cmdlet:

          [-Name] <string> [-Value] <string>

      The following  commands correctly use the New-Alias cmdlet. The commands
      produce the same result:

          New-Alias -Name utd -Value Update-TypeData
          New-Alias -Name utd Update-TypeData
          New-Alias utd -Value Update-TypeData
          New-Alias utd Update-TypeData

      If the parameter name is not included in the statement as typed, Windows
      PowerShell tries to use the position of the arguments to assign the
      values to parameters.

      The following example is not complete:

          New-Alias utd

      This cmdlet requires values for both the Name and Value parameters.

      In syntax examples, brackets are also used in naming and casting to
      .NET Framework types. In this context, brackets do not indicate an
      element is optional.

  Array Arguments
      Brackets are also used in syntax descriptions to represent an array.
      The following example shows the syntax for the Restart-Service cmdlet:

          Restart-Service [-Name] <string[]> [-Include <string[]>]
              [-Exclude <string[]>] [-Force] [-PassThru] [-Confirm] [-WhatIf]
              [<CommonParameters>]

      The Name parameter requires an argument. Specifically, it requires the
      name of the service to be restarted. It can take a comma-separated list
      of services, as in the following example:

          Restart-Service RasAuto, RasMan, RemoteAccess

SEE ALSO
    Get-Help


about_Comment_Based_Help

TOPIC
    about_Comment_Based_Help

SHORT DESCRIPTION
    Describes how to write comment-based Help topics for functions and scripts.

LONG DESCRIPTION
    You can write comment-based Help topics for functions and scripts by using
    special Help comment keywords.

    The Get-Help cmdlet displays comment-based Help in the same format in which
    it displays the cmdlet Help topics that are generated from XML files. Users
    can use all of the parameters of Get-Help, such as Detailed, Full, Example,
    and Online, to display function and script Help.

    You can also write XML-based Help files for scripts and functions by using
    Help comment keywords, and you can redirect users to a different Help file.

    This topic explains how to write Help topics for functions and scripts. For
    information about how to display Help topics for functions and scripts, see
    Get-Help.

 SYNTAX FOR COMMENT-BASED HELP
    The syntax for comment-based Help is as follows:

        # .< help keyword>
        # <help content>

    -or -

        <#
            .< help keyword>
            < help content>
        #>

    Comment-based Help is written as a series of comments. You can type a
    comment symbol (#) before each line of comments, or you can use the "<#" and "#>"
    symbols to create a comment block. All the lines within the comment block are
    interpreted as comments.

    All of the lines in a comment-based Help topic must be contiguous. If a
    comment-based Help topic follows a comment that is not part of the Help
    topic, there must be at least one blank line between the last non-Help
    comment line and the beginning of the comment-based Help.

    Keywords define each section of comment-based Help. Each comment-based Help
    keyword is preceded by a dot (.). The keywords can appear in any order. The
    keyword names are not case-sensitive.

    For example, the Description keyword precedes a description of a function or
    script.

        <#
        .Description
            Get-Function displays the name and syntax of all functions in the session.
        #>

    The comment block must contain at least one keyword. Some of the keywords,
    such as EXAMPLE, can appear many times in the same comment block. The Help
    content for each keyword begins on the line after the keyword and can span
    multiple lines.

 SYNTAX FOR COMMENT-BASED HELP IN FUNCTIONS

    Comment-based Help for a function can appear in one of three locations:

        -- At the beginning of the function body.

        -- At the end of the function body.

        -- Before the Function keyword. There cannot be more than one blank
           line between the last line of the function Help and the Function
           keyword.

    For example:

        function MyFunction
        {
            <#
            .< help keyword>
            < help content>
            #>

            <function commands>
        }

    -or -

        function MyFunction
        {
            <function commands>

            <#
            .< help keyword>
            < help content>
            #>
        }

    -or -

        <#
        .< help keyword>
        < help content>
        #>
        function MyFunction { }

 SYNTAX FOR COMMENT-BASED HELP IN SCRIPTS

    Comment-based Help for a script can appear in one of the following two
    locations in the script.

    -- At the beginning of the script file. Script Help can be preceded in the
       script only by comments and blank lines.

    -- If the first item in the script body (after the Help) is a function
       declaration, there must be at least two blank lines between the end of the
       script Help and the function declaration. Otherwise, the Help is
       interpreted as being Help for the function, not Help for the script.

    -- At the end of the script file.

    For example:

        <#
        .< help keyword>
        < help content>
        #>

        function MyFunction { }

    -or-

        function MyFunction { }

        <#
        .< help keyword>
        < help content>
        #>

 COMMENT-BASED HELP KEYWORDS
    The following are valid comment-based Help keywords. They are listed in the order in
    which they typically appear in a Help topic along with their intended use.
    These keywords can appear in any order in the comment-based Help, and they
    are not case-sensitive.

    .SYNOPSIS
        A brief description of the function or script. This keyword can be used
        only once in each topic.

    .DESCRIPTION
        A detailed description of the function or script. This keyword can be
        used only once in each topic.

    .PARAMETER  <Parameter-Name>
        The description of a parameter. You can include a Parameter keyword for
        each parameter in the function or script syntax.

        The Parameter keywords can appear in any order in the comment block, but
        the function or script syntax determines the order in which the parameters
        (and their descriptions) appear in Help topic. To change the order,
        change the syntax.

        You can also specify a parameter description by placing a comment in the
        function or script syntax immediately before the parameter variable name.
        If you use both a syntax comment and a Parameter keyword, the description
        associated with the Parameter keyword is used, and the syntax comment is
        ignored.

    .EXAMPLE
        A sample command that uses the function or script, optionally followed
        by sample output and a description. Repeat this keyword for each example.

    .INPUTS
        The Microsoft .NET Framework types of objects that can be piped to the
        function or script. You can also include a description of the input
        objects.

    .OUTPUTS
        The .NET Framework type of the objects that the cmdlet returns. You can
        also include a description of the returned objects.

    .NOTES
        Additional information about the function or script.

    .LINK
        The name of a related topic. Repeat this keyword for each related topic.

        This content appears in the Related Links section of the Help topic.

        The Link keyword content can also include a Uniform Resource Identifier
        (URI) to an online version of the same Help topic. The online version
        opens when you use the Online parameter of Get-Help. The URI must begin
        with "http" or "https".

    .COMPONENT
        The technology or feature that the function or script uses, or to which
        it is related. This content appears when the Get-Help command includes
        the Component parameter of Get-Help.

    .ROLE
        The user role for the Help topic. This content appears when the Get-Help
        command includes the Role parameter of Get-Help.

    .FUNCTIONALITY
        The intended use of the function. This content appears when the Get-Help
        command includes the Functionality parameter of Get-Help.

    .FORWARDHELPTARGETNAME <Command-Name>
        Redirects to the Help topic for the specified command. You can redirect
        users to any Help topic, including Help topics for a function, script,
        cmdlet, or provider.

    .FORWARDHELPCATEGORY  <Category>
        Specifies the Help category of the item in ForwardHelpTargetName.
        Valid values are Alias, Cmdlet, HelpFile, Function, Provider, General,
        FAQ, Glossary, ScriptCommand, ExternalScript, Filter, or All. Use this
        keyword to avoid conflicts when there are commands with the same name.

    .REMOTEHELPRUNSPACE <PSSession-variable>
        Specifies a session that contains the Help topic. Enter a variable that
        contains a PSSession. This keyword is used by the Export-PSSession
        cmdlet to find the Help topics for the exported commands.

    .EXTERNALHELP  <XML Help File Path>
        Specifies the path to an XML-based Help file for the script or function.

        In Windows Vista and later versions of Windows, if the specified path
        to the XML file contains UI-culture-specific subdirectories, Get-Help
        searches the subdirectories recursively for an XML file with the name
        of the script or function in accordance with the language fallback
        standards established for Windows Vista, just as it does for all
        XML-based Help topics.

        For more information about the cmdlet Help XML-based Help file format,
        see "How to Create Cmdlet Help" in the MSDN (Microsoft Developer Network)
        library at http://go.microsoft.com/fwlink/?LinkID=123415.

 AUTOGENERATED CONTENT
    The name, syntax, parameter list, parameter attribute table, common
    parameters, and remarks are automatically generated by the Get-Help cmdlet.

        Name:
            The Name section of a function Help topic is taken from the function
            name in the function syntax. The Name of a script Help topic is
            taken from the script file name. To change the name or its
            capitalization, change the function syntax or the script file name.

        Syntax:
            The Syntax section of the Help topic is generated from the function
            or script syntax. To add detail to the Help topic syntax, such as
            the .NET Framework type of a parameter, add the detail to the syntax.
            If you do not specify a parameter type, the "Object" type is
            inserted as the default value.

        Parameter List:
            The Parameter list in the Help topic is generated from the function
            or script syntax and from the descriptions that you add by using the
            Parameters keyword. The function parameters appear in the "Parameters"
            section of the Help topic in the same order that they appear in
            the function or script syntax. The spelling and capitalization of
            parameter names is also taken from the syntax; it is not affected
            by the parameter name specified by the Parameter keyword.

        Common Parameters:
            The common parameters are added to the syntax and parameter list
            of the Help topic, even if they have no effect. For more information
            about the common parameters, see about_CommonParameters.

        Parameter Attribute Table:
            Get-Help generates the table of parameter attributes that appears
            when you use the Full or Parameter parameter of Get-Help. The value
            of the Required, Position, and Default value attributes is taken
            from the function or script syntax.

        Remarks:
            The Remarks section of the Help topic is automatically generated
            from the function or script name. You cannot change or affect its
            content.

EXAMPLES

    Example 1: Comment-based Help for a Function

        The following sample function includes comment-based Help:

            function Add-Extension
            {
                param ([string]$Name,[string]$Extension = "txt")
                $name = $name + "." + $extension
                $name

            <#
            .SYNOPSIS
            Adds a file name extension to a supplied name.

            .DESCRIPTION
            Adds a file name extension to a supplied name.
            Takes any strings for the file name or extension.

            .PARAMETER Name
            Specifies the file name.

            .PARAMETER Extension
            Specifies the extension. "Txt" is the default.

            .INPUTS
            None. You cannot pipe objects to Add-Extension.

            .OUTPUTS
            System.String. Add-Extension returns a string with the extension or file name.

            .EXAMPLE
            C:\PS> extension -name "File"
            File.txt

            .EXAMPLE
            C:\PS> extension -name "File" -extension "doc"
            File.doc

            .EXAMPLE
            C:\PS> extension "File" "doc"
            File.doc

            .LINK
            Online version: http://www.fabrikam.com/extension.html

            .LINK
            Set-Item
            #>
            }

        The results are as follows:

        C:\PS> get-help add-extension -full

        NAME
            Add-Extension

        SYNOPSIS
            Adds a file name extension to a supplied name.

        SYNTAX
            Add-Extension [[-Name] <String>] [[-Extension] <String>] [<CommonParameters>]

        DESCRIPTION
            Adds a file name extension to a supplied name. Takes any strings for the file name or extension.

        PARAMETERS
           -Name
               Specifies the file name.

               Required?                    false
               Position?                    0
               Default value
               Accept pipeline input?       false
               Accept wildcard characters?

           -Extension
               Specifies the extension. "Txt" is the default.

               Required?                    false
               Position?                    1
               Default value
               Accept pipeline input?       false
               Accept wildcard characters?

            <CommonParameters>
               This cmdlet supports the common parameters: -Verbose, -Debug,
               -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
               -OutBuffer and -OutVariable. For more information, type
               "get-help about_commonparameters".

        INPUTs
            None. You cannot pipe objects to Add-Extension.

        OUTPUTS
            System.String. Add-Extension returns a string with the extension or file name.

            -------------------------- EXAMPLE 1 --------------------------

            C:\PS> extension -name "File"
            File.txt

            -------------------------- EXAMPLE 2 --------------------------

            C:\PS> extension -name "File" -extension "doc"
            File.doc

            -------------------------- EXAMPLE 3 --------------------------

            C:\PS> extension "File" "doc"
            File.doc

        RELATED LINKS
            Online version: http://www.fabrikam.com/extension.html
            Set-Item

    Example 2: Parameter Descriptions in Function Syntax

        This example is the same as the previous one, except that the parameter
        descriptions are inserted in the function syntax. This format is most
        useful when the descriptions are brief.

        function Add-Extension
        {
            param
            (
                [string]
                # Specifies the file name.
                $name,

                [string]
                # Specifies the file name extension. "Txt" is the default.
                $extension = "txt"
            )
            $name = $name + "." + $extension
            $name

            <#
            .SYNOPSIS
            Adds a file name extension to a supplied name.

            .DESCRIPTION
            Adds a file name extension to a supplied name. Takes any strings for the file name or extension.

            .INPUTS
            None. You cannot pipe objects to Add-Extension.

            .OUTPUTS
            System.String. Add-Extension returns a string with the extension or file name.

            .EXAMPLE
            C:\PS> extension -name "File"
            File.txt

            .EXAMPLE
            C:\PS> extension -name "File" -extension "doc"
            File.doc

            .EXAMPLE
            C:\PS> extension "File" "doc"
            File.doc

            .LINK
            Online version: http://www.fabrikam.com/extension.html

            .LINK
            Set-Item
            #>
        }

    Example 3: Comment-based Help for a Script

        The following sample script includes comment-based Help.

        Notice the blank lines between the closing "#>" and the Param statement.
        In a script that does not have a Param statement, there must be at least
        two blank lines between the final comment in the Help topic and the first
        function declaration. Without these blank lines, Get-Help associates the
        Help topic with the function, not the script.

           <#
           .SYNOPSIS
           Performs monthly data updates.

           .DESCRIPTION
           The Update-Month.ps1 script updates the registry with new data generated
           during the past month and generates a report.

           .PARAMETER InputPath
           Specifies the path to the CSV-based input file.

           .PARAMETER OutputPath
           Specifies the name and path for the CSV-based output file. By default,
           MonthlyUpdates.ps1 generates a name from the date and time it runs, and
           saves the output in the local directory.

           .INPUTS
           None. You cannot pipe objects to Update-Month.ps1.

           .OUTPUTS
           None. Update-Month.ps1 does not generate any output.

           .EXAMPLE
           C:\PS> .\Update-Month.ps1

           .EXAMPLE
           C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv

           .EXAMPLE
           C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPath C:\Reports\2009\January.csv
           #>

           param ([string]$InputPath, [string]$OutPutPath)

           function Get-Data { }
           ...

        The following command gets the script Help. Because the script is not
        in a directory that is listed in the Path environment variable, the
        Get-Help command that gets the script Help must specify the script path.

            PS C:\ps-test> get-help .\update-month.ps1 -full

            NAME
                C:\ps-test\Update-Month.ps1

            SYNOPSIS
                Performs monthly data updates.

            SYNTAX
                C:\ps-test\Update-Month.ps1 [-InputPath] <String> [[-OutputPath]
                <String>] [<CommonParameters>]

            DESCRIPTION
                The Update-Month.ps1 script updates the registry with new data
                generated during the past month and generates a report.

            PARAMETERS
               -InputPath
                   Specifies the path to the CSV-based input file.

                   Required?                    true
                   Position?                    0
                   Default value
                   Accept pipeline input?       false
                   Accept wildcard characters?

               -OutputPath
                   Specifies the name and path for the CSV-based output file. By
                   default, MonthlyUpdates.ps1 generates a name from the date
                   and time it runs, and saves the output in the local directory.

                   Required?                    false
                   Position?                    1
                   Default value
                   Accept pipeline input?       false
                   Accept wildcard characters?

               <CommonParameters>
                   This cmdlet supports the common parameters: -Verbose, -Debug,
                   -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
                   -OutBuffer and -OutVariable. For more information, type,
                   "get-help about_commonparameters".

            INPUTS
                   None. You cannot pipe objects to Update-Month.ps1.

            OUTPUTS
                   None. Update-Month.ps1 does not generate any output.

            -------------------------- EXAMPLE 1 --------------------------

            C:\PS> .\Update-Month.ps1

            -------------------------- EXAMPLE 2 --------------------------

            C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv

            -------------------------- EXAMPLE 3 --------------------------

            C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPath
            C:\Reports\2009\January.csv

            RELATED LINKS

    Example 4:  Redirecting to an XML File

        You can write XML-based Help topics for functions and scripts. Although
        comment-based Help is easier to implement, XML-based Help is required
        if you want more precise control over Help content or if you are
        translating Help topics into multiple languages.

        The following example shows the first few lines of the Update-Month.ps1
        script. The script uses the ExternalHelp keyword to specify the path to
        an XML-based Help topic for the script.

            #  .ExternalHelp C:\MyScripts\Update-Month-Help.xml

            param ([string]$InputPath, [string]$OutPutPath)

            function Get-Data { }
            ...

       The following example shows the use of the ExternalHelp keyword in a
       function.

            function Add-Extension
            {
                param ([string] $name, [string]$extension = "txt")
                $name = $name + "." + $extension
                $name

                # .ExternalHelp C:\ps-test\Add-Extension.xml
            }

    Example 5:  Redirecting to a Different Help Topic

        The following code is an excerpt from the beginning of the built-in
        Help function in Windows PowerShell, which displays one screen of Help
        text at a time. Because the Help topic for the Get-Help cmdlet describes
        the Help function, the Help function uses the ForwardHelpTargetName and
        ForwardHelpCategory keywords to redirect the user to the Get-Help cmdlet
        Help topic.

            function help
            {

            <#
            .FORWARDHELPTARGETNAME Get-Help
            .FORWARDHELPCATEGORY Cmdlet
            #>
            [CmdletBinding(DefaultParameterSetName='AllUsersView')]
            param(
                [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)]
                [System.String]
                ${Name},
                   ...

        The following command uses this feature:

            C:\PS> get-help help

            NAME
                Get-Help

            SYNOPSIS
                Displays information about Windows PowerShell cmdlets and concepts.
            ...

SEE ALSO
    about_Functions
    about_Functions_Advanced_Parameters
    about_Scripts
    "How to Write Cmdlet Help" (http://go.microsoft.com/fwlink/?LinkID=123415)


about_CommonParameters

TOPIC
    about_CommonParameters

SHORT DESCRIPTION
    Describes the parameters that can be used with any cmdlet.

LONG DESCRIPTION
    The common parameters are a set of cmdlet parameters that you can
    use with any cmdlet. They are implemented by Windows PowerShell, not
    by the cmdlet developer, and they are automatically available to any
    cmdlet.

    You can use the common parameters with any cmdlet, but they might
    not have an effect on all cmdlets. For example, if a cmdlet does not
    generate any verbose output, using the Verbose common parameter
    has no effect.

    Several common parameters override system defaults or preferences
    that you set by using the Windows PowerShell preference variables. Unlike
    the preference variables, the common parameters affect only the commands
    in which they are used.

    In addition to the common parameters, many cmdlets offer the WhatIf and
    Confirm risk mitigation parameters. Cmdlets that involve risk to the system
    or to user data usually offer these parameters.

    The common parameters are:

       -Verbose
       -Debug
       -WarningAction
       -WarningVariable
       -ErrorAction
       -ErrorVariable
       -OutVariable
       -OutBuffer

    The risk mitigation parameters are:

       -WhatIf
       -Confirm

    For more information about preference variables, type:

       help about_preference_variables

  Common Parameter Descriptions

    -Verbose[:{$true | $false}]

        Displays detailed information about the operation performed by the
        command. This information resembles the information in a trace or in
        a transaction log. This parameter works only when the command generates
        a verbose message. For example, this parameter works when a command
        contains the Write-Verbose cmdlet.

        The Verbose parameter overrides the value of the $VerbosePreference
        variable for the current command. Because the default value of the
        $VerbosePreference variable is SilentlyContinue, verbose messages
        are not displayed by default.

        Valid values:

            $true (-Verbose:$true) has the same effect as -Verbose.

            $false (-Verbose:$false) suppresses the display of verbose
            messages. Use this parameter when the value of $VerbosePreference
            is not SilentlyContinue (the default).

    -Debug[:{$true | $false}]

        Displays programmer-level detail about the operation performed by the
        command. This parameter works only when the command generates
        a debugging message. For example, this parameter works when a command
        contains the Write-Debug cmdlet.

        The Debug parameter overrides the value of the $DebugPreference
        variable for the current command. Because the default value of the
        $DebugPreference variable is SilentlyContinue, debugging messages
        are not displayed by default.

        Valid values:

            $true (-Debug:$true). Has the same effect as -Debug.

            $false (-Debug:$false). Suppresses the display of debugging
            messages when the value of the $DebugPreference is not
            SilentlyContinue (the default).

    -WarningAction[:{SilentlyContinue | Continue | Inquire | Stop}]

        Determines how the cmdlet responds to a warning from the command.
        "Continue" is the default value. This parameter works only
        when the command generates a warning message. For example, this
        parameter works when a command contains the Write-Warning cmdlet.

        The WarningAction parameter overrides the value of the
        $WarningPreference variable for the current command. Because the
        default value of the $WarningPreference variable is Continue,
        warnings are displayed and execution continues unless you use the
        WarningAction parameter.

         Valid Values:

            SilentlyContinue. Suppresses the warning message and continues
            executing the command.

            Continue. Displays the warning message and continues executing
            the command. "Continue" is the default value.

            Inquire. Displays the warning message and prompts you for
            confirmation before continuing execution. This value is rarely
            used.

            Stop. Displays the warning message and stops executing the
            command.

    -WarningVariable [+]<variable-name>

        Stores warnings about the command in the specified variable.

        To append the warnings to the variable content, instead of replacing
        any warnings that might already be stored there, type a plus sign (+)
        before the variable name.

        For example, the following command creates the $a variable and then
        stores any warnings in it:

            get-process -id 6 -WarningVariable a

        The following command adds any warnings to the $a variable:

            get-process -id 2 -WarningVariable +a

        The following command displays the contents of $a:

            $a

        You can use this parameter to create a variable that contains only
        warnings from specific commands. You can use array notation, such as
        $a[0] or $warning[1,2] to refer to specific warnings stored in the
        variable.

    -ErrorAction[:{SilentlyContinue | Continue | Inquire | Stop)]

        Determines how the cmdlet responds to a non-terminating error
        from the command. This parameter works only when the command generates
        a debugging message. For example, this parameters works when a command
        contains the Write-Error cmdlet.

        The ErrorAction parameter overrides the value of the
        $ErrorActionPreference variable for the current command.
        Because the default value of the $ErrorActionPreference variable
        is Continue, error messages are displayed and execution continues
        unless you use the ErrorAction parameter.

        The ErrorAction parameter has no effect on terminating errors (such as
        missing data, parameters that are not valid, or insufficient
        permissions) that prevent a command from completing successfully.

        Valid values:

            SilentlyContinue. Suppresses the error message and continues
            executing the command.

            Continue. Displays the error message and continues executing
            the command. "Continue" is the default value.

            Inquire. Displays the error message and prompts you for
            confirmation before continuing execution. This value is rarely
            used.

            Stop. Displays the error message and stops executing the
            command.

    -ErrorVariable [+]<variable-name>

        Stores error messages about the command in the specified variable
        and in the $Error automatic variable. For more information,
        type the following command:

            get-help about_automatic_variables

        By default, new error messages overwrite error messages that are
        already stored in the variable. To append the error message to the
        variable content, type  a plus sign (+) before the variable name.

        For example, the following command creates the $a variable and then
        stores any errors in it:

            get-process -id 6 -ErrorVariable a

        The following command adds any error messages to the $a variable:

            get-process -id 2 -ErrorVariable +a

        The following command displays the contents of $a:

            $a

        You can use this parameter to create a variable that contains only
        error messages from specific commands. The $Error automatic
        variable contains error messages from all the commands in the session.
        You can use array notation, such as $a[0] or $error[1,2] to refer to
        specific errors stored in the variables.

    -OutVariable [+]<variable-name>

        Stores output objects from the command in the specified variable and
        displays it at the command line.

        To add the output to the variable, instead of replacing any output
        that might already be stored there, type a plus sign (+) before the
        variable name.

        For example, the following command creates the $out variable and
        stores the process object in it:

            get-process powershell -OutVariable out

        The following command adds the process object to the $out variable:

            get-process iexplore -OutVariable +out

        The following command displays the contents of the $out variable:

            $out

    -OutBuffer <Int32>

        Determines the number of objects to accumulate in a buffer before
        any objects are sent through the pipeline. If you omit this parameter,
        objects are sent as they are generated.

        This resource management parameter is designed for advanced users.
        When you use this parameter, Windows PowerShell does not call the
        next cmdlet in the pipeline until the number of objects generated
        equals OutBuffer + 1. Thereafter, it sends all objects as they are
        generated.

  Risk Management Parameter Descriptions

    -WhatIf[:{$true | $false}]
        Displays a message that describes the effect of the command,
        instead of executing the command.

        The WhatIf parameter overrides the value of the $WhatIfPreference
        variable for the current command. Because the default value of the
        $WhatIfPreference variable is 0 (disabled), WhatIf behavior is not
        performed without the WhatIf parameter. For more information, type
        the following command:

            get-help about_preference_variables

        Valid values:

            $true (-WhatIf:$true). Has the same effect as -WhatIf.

            $false (-WhatIf:$false). Suppresses the automatic WhatIf behavior
            that results when the value of the $WhatIfPreference variable
            is 1.

        For example, the following command uses the WhatIf parameter in a
        Remove-Item command:

            PS> remove-item date.csv -whatif

        Instead of removing the item, Windows PowerShell lists the operations
        it would perform and the items that would be affected. This command
        produces the following output:

            What if: Performing operation "Remove File" on
            Target "C:\ps-test\date.csv".

    -Confirm[:{$true | $false}]
        Prompts you for confirmation before executing the command.

        The Confirm parameter overrides the value of the $ConfirmPreference
        variable for the current command. The default value is High. For more
        information, type the following command:

            get-help about_preference_variables

        Valid values:

            $true (-WhatIf:$true). Has the same effect as -Confirm.

            $false(-Confirm:$false). Suppresses automatic confirmation,
            which occurs when the value of $ConfirmPreference is less than
            or equal to the estimated risk of the cmdlet.

        For example, the following command uses the Confirm parameter with a
        Remove-Item command. Before removing the item, Windows PowerShell
        lists the operations it would perform and the items that would be
        affected, and asks for approval.

            PS C:\ps-test> remove-item tmp*.txt -confirm

        This command produces the following output:

            Confirm
            Are you sure you want to perform this action?
            Performing operation "Remove File" on Target " C:\ps-test\tmp1.txt
            [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend
            [?] Help (default is "Y"):

SEE ALSO
    about_Preference_Variables
    Write-Debug
    Write-Warning
    Write-Error
    Write-Verbose


about_Comparison_Operators

TOPIC
    about_Comparison_Operators

SHORT DESCRIPTION
    Describes the operators that compare values in Windows PowerShell.

LONG DESCRIPTION
    Comparison operators let you specify conditions for comparing values and
    finding values that match specified patterns. To use a comparison operator,
    specify the values that you want to compare together with an operator that
    separates these values.

    By default, all comparison operators are case-insensitive. To make a
    comparison operator case-sensitive, precede the operator name with a "c".
    For example, the case-sensitive version of "-eq" is "-ceq". To make the
    case-insensitivity explicit, precede the operator with an "i". For example,
    the explicitly case-insensitive version of "-eq" is "ieq".

    All comparison operators except the containment operators
    (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean
    value when the input to the operator (the value on the left side of the
    operator) is a single value (a scalar). When the input is a collection of
    values, the containment operators and the type operators return any
    matching values. If there are no matches in a collection, these operators
    do not return anything. The containment operators and type operators always
    return a Boolean value.

    Windows PowerShell supports the following comparison operators.

    -eq
      Description: Equal to. Includes an identical value.
      Example:

          C:\PS> "abc", "def" -eq "abc"
          abc

    -ne
      Description: Not equal to. Includes a different value.
      Example:

          C:\PS> "abc", "def" -ne "abc"
          def

    -gt
      Description: Greater-than.
      Example:

          C:\PS> 8 -gt 6
          True

    -ge
      Description: Greater-than or equal to.
      Example:

          C:\PS> 8 -ge 8
          True

    -lt
      Description: Less-than.
      Example:

          C:\PS> 8 -lt 6
          False

    -le
      Description: Less-than or equal to.
      Example:

          C:\PS> 6 -le 8
          True

    -like
      Description: Match using the wildcard character (*).
      Example:

          C:\PS> "Windows PowerShell" -like "*shell"
          True

    -notlike
      Description: Does not match using the wildcard character (*).
      Example:

          C:\PS> "Windows PowerShell" -notlike "*shell"
          False

    -match
      Description: Matches a string using regular expressions.
                   When the input is scalar, it populates the
                   $Matches automatic variable.
      Example:

          C:\PS> "Sunday" -match "sun"
          True

          C:\PS> $matches
          Name Value
          ---- -----
          0    sun

    -notmatch
      Description: Does not match a string. Uses regular expressions.
                   When the input is scalar, it populates the $Matches
                   automatic variable.
      Example:

          C:\PS> "Sunday" -notmatch "sun"
          False

          C:\PS> $matches
          Name Value
          ---- -----
          0    sun

    -contains
      Description: Containment operator. Includes an  identical value that is
      not part of a value. Always returns a Boolean value.
      Example:

          C:PS> "abc", "def" -contains "def"
          True

    -notcontains
      Description: Containment operator. Does not include an identical value.
      Always returns Boolean.
      Example:

          C:PS> "Windows", "PowerShell" -notcontains "Shell"
          True

    -replace
      Description: Replace operator. Changes the specified elements of a value.
      Example:

          C:\PS> "Get-Process" -replace "Get", "Stop"
          Stop-Process

  Equality Operators
      The equality operators (-eq, -ne) return a value of TRUE or the matches
      when one or more of the input values is identical to the specified
      pattern. The entire pattern must match an entire value.

      The following examples show the effect of the equal to operator:

          C:PS> 1,2,3 -eq 2
          2

          C:PS> "PowerShell" -eq "Shell"
          False

          C:PS> "Windows", "PowerShell" -eq "Shell"
          C:PS>

          C:\PS> "abc", "def", "123" -eq "def"
          def

  Containment Operators
      The containment operators (-contains and -notcontains) are similar to the
      equality operators. However, the containment operators always return a
      Boolean value, even when the input is a collection.

      Also, unlike the equality operators, the containment operators return a
      value as soon as they detect the first match. The equality operators
      evaluate all input and then return all the matches in the collection.
      The following examples show the effect of the -contains operator:

          C:PS> 1,2,3 -contains 2
          True

          C:PS> "PowerShell" -contains "Shell"
          False

          C:PS> "Windows", "PowerShell" -contains "Shell"
          False

          C:\PS> "abc", "def", "123" -contains "def"
          True

          C:\PS> "true", "blue", "six" -contains "true"
          True

      The following example shows how the containment operators differ from the
      equal to operator. The containment operators return a value of TRUE on the
      first match.

          C:\PS> 1,2,3,4,5,4,3,2,1 -eq 2
          2
          2

          C:\PS> 1,2,3,4,5,4,3,2,1 -contains 2
          True

      In a very large collection, the -contains operator returns results
      quicker than the equal to operator.

  Match Operators
      The match operators (-match and -notmatch) find elements that match or
      do not match a specified pattern using regular expressions.

      The syntax is:

          <string[]> -match <regular-expression>
          <string[]> -notmatch <regular-expression>

      The following examples show some uses of the -match operator:

          C:\PS> "Windows", "PowerShell" -match ".shell"
          PowerShell

          C:\PS> (get-command get-member -syntax) -match "-view"
          True

          C:\PS> (get-command get-member -syntax) -notmatch "-path"
          True

          C:\PS> (get-content servers.txt) -match "^Server\d\d"
          Server01
          Server02

      The match operators search only in strings. They cannot search in arrays
      of integers or other objects.

      The -match and -notmatch operators populate the $Matches automatic
      variable when the input (the left-side argument) to the operator
      is a single scalar object. When the input is scalar, the -match and
      -notmatch operators return a Boolean value and set the value of the
      $Matches automatic variable to the matched components of the argument.

      If the input is a collection, the -match and -notmatch operators return
      the matching members of that collection, but the operator does not
      populate the $Matches variable.

      For example, the following command submits a collection of strings to
      the -match operator. The -match operator returns the items in the collection
      that match. It does not populate the $Matches automatic variable.

          C:\PS> "Sunday", "Monday", "Tuesday" -match "sun"
          Sunday

          C:\PS> $matches
          C:\PS>

      In contrast, the following command submits a single string to the
      -match operator. The -match operator returns a Boolean value and
      populates the $Matches automatic variable.

          C:\PS> "Sunday" -match "sun"
          True

          C:\PS> $matches

          Name                           Value
          ----                           -----
          0                              Sun

      The -notmatch operator populates the $Matches automatic variable when
      the input is scalar and the result is False, that it, when it detects
      a match.

          C:\PS> "Sunday" -notmatch "rain"
          True

          C:\PS> $matches
          C:\PS>

          C:\PS> "Sunday" -notmatch "day"
          False

          C:\PS> $matches
          C:\PS>

          Name                           Value
          ----                           -----
          0                              day

  Replace Operator
      The -replace operator replaces all or part of a value with the specified
      value using regular expressions. You can use the -replace operator for
      many administrative tasks, such as renaming files. For example, the
      following command changes the file name extensions of all .gif files
      to .jpg:

          Get-ChildItem | Rename-Item -NewName { $_ -replace '.gif$','.jpg$' }

      The syntax of the -replace operator is as follows, where the <original>
      placeholder represents the characters to be replaced, and the
      <substitute> placeholder represents the characters that will replace
      them:

          <input> <operator> <original>, <substitute>

      By default, the -replace operator is case-insensitive. To make it case
      sensitive, use -creplace. To make it explicitly case-insensitive, use
      -ireplace. Consider the following examples:

          C:\PS> "book" -replace "B", "C"
          Cook
          C:\PS> "book" -ireplace "B", "C"
          Cook
          C:\PS> "book" -creplace "B", "C"
          book

  Bitwise Operators
      Windows PowerShell supports the standard bitwise operators, including
      bitwise-AND (-band), and inclusive and exclusive bitwise-OR operators
      (-bor and -bxor). Beginning in Windows PowerShell 2.0, all bitwise
      operators work with 64-bit integers.

      Windows PowerShell supports the following bitwise operators.

      Operator  Description               Example
      --------  ----------------------    -------------------
      -band     Bitwise AND               C:\PS> 10 -band 3
                                          2

      -bor      Bitwise OR (inclusive)    C:\PS> 10 -bor 3
                                          11

      -bxor     Bitwise OR (exclusive)    C:\PS> 10 -bxor 3
                                          9

      Bitwise operators act on the binary format of a value. For example, the
      bit structure for the number 10 is 00001010 (based on 1 byte), and the
      bit structure for the number 3 is 00000011. When you use a bitwise
      operator to compare 10 to 3, the individual bits in each byte are
      compared.

      In a bitwise AND operation, the resulting bit is set to 1 only when both
      input bits are 1.

          00001010      (10)
          00000011      ( 3)
          ------------------  bAND
          00000010      ( 2)

      In a bitwise OR (inclusive) operation, the resulting bit is set to 1
      when either or both input bits are 1. The resulting bit is set to 0 only
      when both input bits are set to 0.

          00001010      (10)
          00000011      ( 3)
          ------------------  bOR (inclusive)
          00001011      (11)

      In a bitwise OR (exclusive) operation, the resulting bit is set to 1 only
      when one input bit is 1.

          00001010      (10)
          00000011      ( 3)
          ------------------  bXOR (exclusive)
          00001001      ( 9)

SEE ALSO
    about_Operators
    about_Regular_Expressions
    about_Wildcards
    Compare-Object


about_Continue

TOPIC
    about_Continue

SHORT DESCRIPTION
    Describes how the Continue statement immediately returns the program flow
    to the top of a program loop.

LONG DESCRIPTION
    In a script, the Continue statement immediately returns the program flow
    to the top of the innermost loop that is controlled by a For, Foreach, or
    While statement.

    The Continue keyword supports labels. A label is a name you assign to a
    statement in a script. For information about labels, see about_Break.

    In the following example, program flow returns to the top of the While loop
    if the $ctr variable is equal to 5. As a result, all the numbers between 1
    and 10 are displayed except for 5:

        while ($ctr -lt 10)
             {
               $ctr +=1
               if ($ctr -eq 5) {continue}
               Write-Host $ctr
             }

    Note that in a For loop, execution continues at the first line in the
    loop. If the arguments of the For statement test a value that is
    modified by the For statement, an infinite loop may result.

SEE ALSO
    about_Comparison_Operators


about_Core_Commands

TOPIC
    about_Core_Commands

SHORT DESCRIPTION
    Lists the cmdlets that are designed for use with Windows PowerShell
    providers.

LONG DESCRIPTION
    Windows PowerShell includes a set of cmdlets that are specifically
    designed to manage the items in the data stores that are exposed by Windows
    PowerShell providers. You can use these cmdlets in the same ways to manage
    all the different types of data that the providers make available to you.
    For more information about providers, type "get-help about_providers".

    For example, you can use the Get-ChildItem cmdlet to list the files in a
    file system directory, the keys under a registry key, or the items that are
    exposed by a provider that you write or download.

    The following is a list of the Windows PowerShell cmdlets that are designed
    for use with providers:

  ChildItem cmdlets
      Get-ChildItem

  Content cmdlets
      Add-Content
      Clear-Content
      Get-Content
      Set-Content

  Item cmdlets
      Clear-Item
      Copy-Item
      Get-Item
      Invoke-Item
      Move-Item
      New-Item
      Remove-Item
      Rename-Item
      Set-Item

  ItemProperty cmdlets
      Clear-ItemProperty
      Copy-ItemProperty
      Get-ItemProperty
      Move-ItemProperty
      New-ItemProperty
      Remove-ItemProperty
      Rename-ItemProperty
      Set-ItemProperty

  Location cmdlets
      Get-Location
      Pop-Location
      Push-Location
      Set-Location

  Path cmdlets
      Join-Path
      Convert-Path
      Split-Path
      Resolve-Path
      Test-Path

  PSDrive cmdlets
      Get-PSDrive
      New-PSDrive
      Remove-PSDrive

  PSProvider cmdlets
      Get-PSProvider

    For more information about a cmdlet, type "get-help <cmdlet-name>".

SEE ALSO
    about_Providers


about_Data_Sections

TOPIC
    about_Data_Sections

SHORT DESCRIPTION
    Explains Data sections, which isolate text strings and other read-only
    data from script logic.

LONG DESCRIPTION
    Scripts that are designed for Windows PowerShell can have one or more
    Data sections that contain only data. You can include one or more Data
    sections in any script, function, or advanced function. The content of
    the Data section is restricted to a specified subset of the Windows
    PowerShell scripting language.

    Separating data from code logic makes it easier to identify and manage
    both logic and data. It lets you have separate string resource files for
    text, such as error messages and Help strings. It also isolates the code
    logic, which facilitates security and validation tests.

    In Windows PowerShell, the Data section is used to support script
    internationalization. You can use Data sections to make it easier to
    isolate, locate, and process strings that will be translated into many
    user interface (UI) languages.

    The Data section is a Windows PowerShell 2.0 feature. Scripts with Data
    sections will not run in Windows PowerShell 1.0 without revision.

  Syntax

    The syntax for a Data section is as follows:

        DATA [-supportedCommand <cmdlet-name>] {

            <Permitted content>
        }

    The Data keyword is required. It is not case-sensitive.

    The permitted content is limited to the following elements:

        - All Windows PowerShell operators, except -match

        - If, Else, and ElseIf statements

    - The following automatic variables: $PsCulture,  $PsUICulture,  $True,
          $False, and $Null

        - Comments

        - Pipelines

        - Statements separated by semicolons (;)

        - Literals, such as the following:

            a

            1

            1,2,3

            "Windows PowerShell 2.0"

            @( "red", "green", "blue" )

            @{ a = 0x1; b = "great"; c ="script" }

            [XML] @'
             <p> Hello, World </p>
            '@

        - Cmdlets that are permitted in a Data section. By default, only the
          ConvertFrom-StringData cmdlet is permitted.

        - Cmdlets that you permit in a Data section by using the
          SupportedCommand parameter.

    When you use the ConvertFrom-StringData cmdlet in a Data section, you can
    enclose the key/value pairs in single-quoted or double-quoted strings or in
    single-quoted or double-quoted here-strings. However, strings that contain
    variables and subexpressions must be enclosed in single-quoted strings or
    in single-quoted here-strings so that the variables are not expanded and the
    subexpressions are not executable.

  SupportedCommand

      The SupportedCommand parameter allows you to indicate that a cmdlet or
      function generates only data. It is designed to allow users to include
      cmdlets and functions in a data section that they have written or tested.

      The value of SupportedCommand is a comma-separated list of one or more
      cmdlet or function names.

      For example, the following data section includes a user-written cmdlet,
      Format-XML, that formats data in an XML file:

      DATA -supportedCommand Format-XML
          {
             Format-XML -strings string1, string2, string3
          }

  Using a Data Section

      To use the content of a Data section, assign it to a variable and use
      variable notation to access the content.

      For example, the following data section contains a ConvertFrom-StringData
      command that converts the here-string into a hash table. The hash table
      is assigned to the $TextMsgs variable.

      The $TextMsgs variable is not part of the data section.

          $TextMsgs = DATA {
              ConvertFrom-StringData -stringdata @'
                Text001 = Windows 7
                Text002 = Windows Server 2008 R2
          '@
          }

      To access the keys and values in hash table in $TextMsgs, use the
      following commands.

          $TextMsgs.Text001
          $TextMsgs.Text002

EXAMPLES

    Simple data strings.

        DATA {
            "Thank you for using my Windows PowerShell Organize.pst script."
            "It is provided free of charge to the community."
            "I appreciate your comments and feedback."
        }

    Strings that include permitted variables.

        DATA {
            if ($null) {
           "To get help for this cmdlet, type get-help new-dictionary."
            }
        }

    A single-quoted here-string that uses the ConvertFrom-StringData cmdlet:

        DATA {
          ConvertFrom-StringData -stringdata @'
            Text001 = Windows 7
            Text002 = Windows Server 2008 R2
        '@
        }

    A double-quoted here-string that uses the ConvertFrom-StringData cmdlet:

        DATA  {
          ConvertFrom-StringData -stringdata @"
            Msg1 = To start, press any key.
            Msg2 = To exit, type "quit".
        "@
        }

    A data section that includes a user-written cmdlet that generates data:

    DATA -supportedCommand Format-XML {
           Format-XML -strings string1, string2, string3
        }

SEE ALSO
    about_Automatic_Variables
    about_Comparison_Operators
    about_Hash_Tables
    about_If
    about_Operators
    about_Quoting_Rules
    about_Script_Internationalization
    ConvertFrom-StringData
    Import-LocalizedData


about_Debuggers

TOPIC
    about_Debuggers

SHORT DESCRIPTION
    Describes the Windows PowerShell debugger.

LONG DESCRIPTION
    Debugging is the process of examining a script while it is running in
    order to identify and correct errors in the script instructions. The
    Windows PowerShell debugger is designed to help you examine and identify
    errors and inefficiencies in your scripts.

    Note: The Windows PowerShell debugger does not run remotely. To debug
          a script on a remote computer, copy the script to the local
          computer.

    You can use the features of the Windows PowerShell debugger to examine a
    Windows PowerShell script, function, command, or expression while it is
    running. The Windows PowerShell debugger includes a set of cmdlets that
    let you set breakpoints, manage breakpoints, and view the call stack.

    Windows PowerShell offers several methods that you can use to debug
    scripts, functions, and commands.

    Method 1: The Set-PsDebug cmdlet offers basic script debugging features,
              including stepping and tracing. For more information, type:
              "get-help set-psdebug".

    Method 2: Use the Set-StrictMode cmdlet to detect references to
              uninitialized variables, to references to non-existent properties
              of an object, and to function syntax that is not valid.

    Method 3: Add diagnostic statements to a script, such as statements that
              display the value of variables, statements that read input from
              the command line, or statements that report the current
              instruction. Use the cmdlets that contain the Write verb for
              this task, such as Write-Host, Write-Debug, Write-Warning, and
              Write-Verbose.

    Method 4: Use the Windows PowerShell debugger to debug a script. Or, use
              the debugger to debug a function or script block that you typed
              at the command prompt. You can set breakpoints, step through the
              script, examine the values of variables, run diagnostics and
              logging commands, and display the call stack.

  Debugger Cmdlets
      The Windows PowerShell debugger includes the following set of cmdlets:

          Set-PsBreakpoint:     Sets breakpoints on lines, variables, and
                              commands.

          Get-PsBreakpoint:     Gets breakpoints in the current session.

          Disable-PsBreakpoint: Turns off breakpoints in the current session.

          Enable-PsBreakpoint:  Re-enables breakpoints in the current session.

          Remove-PsBreakpoint:  Deletes breakpoints from the current session.

          Get-PsCallStack:      Displays the current call stack.

  Starting and Stopping the Debugger
      To start the debugger, set one or more breakpoints. Then, run the script,
      command, or function that you want to debug.

      When you reach a breakpoint, execution stops, and control is turned over
      to the debugger.

      To stop the debugger, run the script, command, or function until it is
      complete. Or, type "stop" or "t".

  Debugger Commands
      When you use the debugger in the Windows PowerShell console, use the
      following commands to control the execution.

      Note: For information about how to use the debugger in other host
          applications, see the host application documentation.

     s, Step-into        Executes the next statement and then stops.

     v, Step-over        Executes the next statement, but skips functions
                            and invocations. The skipped statements are
                            executed, but not stepped through.

     o, Step-out         Steps out of the current function; up one level
                            if nested. If in the main body, it continues to
                            the end or the next breakpoint. The skipped
                            statements are executed, but not stepped through.

     c, Continue         Continues to run until the script is complete or
                            until the next breakpoint is reached. The skipped
                            statements are executed, but not stepped through.

        l, List             Displays the part of the script that is executing.
                            By default, it displays the current line, five
                            previous lines, and 10 subsequent lines. To continue
                            listing the script, press ENTER.

        l <m>, List         Displays 16 lines of the script beginning with the
                            line number specified by <m>.

        l <m> <n>, List     Displays <n> lines of the script, beginning with the
                            line number specified by <m>.

        q, Stop             Stops executing the script, and exits the debugger.

        k, Get-PsCallStack  Displays the current call stack.

    <Enter>             Repeats the last command if it was Step (s),
                            Step-over (v), or List (l). Otherwise, represents a
                            submit action.

    ?, h                Displays the debugger command Help.

      To exit the debugger, use Stop (q).

      While in the debugger, you can also enter commands, display the value of
      variables, use cmdlets, and run scripts.

      By using these debugger commands, you can run a script, stop on a point
      of concern, examine the values of variables and the state of the system,
      and continue running the script until you have identified a problem.

  The Debugger Environment
      When you reach a breakpoint, you enter the debugger environment. The
      command prompt changes so that it begins with "[DBG]:". You can customize
      the prompt.

      Also, in some host applications, such as the Windows PowerShell console,
      (but not in Windows PowerShell Integrated Scripting Environment [ISE]),
      a nested prompt opens for debugging. You can detect the nested prompt by
      the repeating greater-than characters (ASCII 62) that appear at the
      command prompt.

      For example, the following is the default debugging prompt in the
      Windows PowerShell console:

          [DBG]: PS (get-location)>>>

      You can find the nesting level by using the $NestedPromptLevel
      automatic variable.

      Additionally, an automatic variable, $PSDebugContext, is defined in
      the local scope. You can use the presence of the $PsDebugContext
      variable to determine whether you are in the debugger.

      For example:

          if ($psdebugcontext) {"Debugging"} else {"Not Debugging"}

      You can use the value of the $PSDebugContext variable in your
      debugging.

    [DBG]: PS>>> $psdebugcontext.invocationinfo

        Name   CommandLineParameters  UnboundArguments  Location
        ----   ---------------------  ----------------  --------
        =      {}                     {}                C:\ps-test\vote.ps1 (1)

  Debugging and Scope
      Breaking into the debugger does not change the scope in which
      you are operating, but when you reach a breakpoint in a script,
      you move into the script scope. The script scope is a child
      of the scope in which you ran the debugger.

      To find the variables and aliases that are defined in the
      script scope, use the Scope parameter of the Get-Alias or
      Get-Variable cmdlets.

      For example, the following command gets the variables in the
      local (script) scope:

      get-variable -scope 0

      You can abbreviate the command as:

    gv -s 0

      This is a useful way to see only the variables that you defined in the
      script and that you defined while debugging.

  Debugging at the Command Line
      When you set a variable breakpoint or a command breakpoint, you can set
      the breakpoint only in a script file. However, by default, the breakpoint
      is set on anything that runs in the current session.

      For example, if you set a breakpoint on the $name variable, the debugger
      breaks on any $name variable in any script, command, function, script
      cmdlet or expression that you run until you disable or remove the
      breakpoint.

      This allows you to debug your scripts in a more realistic context in
      which they might be affected by functions, variables, and other scripts
      in the session and in the user's profile.

      Line breakpoints are specific to script files, so they are set only in
      script files.

  Debugging Functions
      When you set a breakpoint on a function that has Begin, Process, and
      End sections, the debugger breaks at the first line of each section.

      For example:

              function test-cmdlet
              {
                  begin
                  {
                      write-output "Begin"
                  }
                  process
                  {
                      write-output "Process"
                  }
                  end
                  {
                      write-output "End"
                  }
              }

          C:\PS> set-psbreakpoint -command test-cmdlet

          C:\PS> test-cmdlet

          Begin
          Entering debug mode. Use h or ? for help.

          Hit Command breakpoint on 'prompt:test-cmdlet'

          test-cmdlet

          [DBG]: C:\PS> c
          Process
          Entering debug mode. Use h or ? for help.

          Hit Command breakpoint on 'prompt:test-cmdlet'

          test-cmdlet

          [DBG]: C:\PS> c
          End
          Entering debug mode. Use h or ? for help.

          Hit Command breakpoint on 'prompt:test-cmdlet'

          test-cmdlet

          [DBG]: C:\PS>

  Debugging Remote Scripts
      You cannot run the Windows PowerShell debugger in a remote session. To
      debug a script on a remote computer, copy the script to the local
      computer.

      The following command copies the Test.ps1 script from the Server01 remote
      computer to the local computer:

          invoke-command -computername Server01 `
          {get-content c:\ps-test\test.ps1} | set-location c:\ps-test\test.ps1

  Examples
      This test script detects the version of the operating system and
      displays a system-appropriate message. It includes a function, a function
      call, and a variable.

      The following command displays the contents of the test script file:

      c:>\PS-test>  get-content test.ps1

      function psversion {
             "Windows Powershell " + $psversiontable.psversion
              if ($psversiontable.psversion.major -lt 2) {
                  "Upgrade to Windows PowerShell 2.0!"
              }
              else {
                  "Have you run a background job today (start-job)?"
              }
          }

      $scriptname = $MyInvocation.MyCommand.Path
      psversion
      "Done $scriptname."

      To start, set a breakpoint at a point of interest in the script, such
      as a line, command, variable, or function.

      Start by creating a line breakpoint on the first line of the Test.ps1
      script in the current directory.

          PS C:\ps-test> set-psbreakpoint -line 1 -script test.ps1

      You can abbreviate this command as:

          PS C:\ps-test> spb 1 -s test.ps1

      The command returns a line-breakpoint object
      (System.Management.Automation.LineBreakpoint).

          Column     : 0
            Line       : 1
            Action     :
            Enabled    : True
            HitCount   : 0
            Id         : 0
            Script     : C:\ps-test\test.ps1
            ScriptName : C:\ps-test\test.ps1

      Now, start the script.

      PS C:\ps-test> .\test.ps1

      When the script reaches the first breakpoint, the breakpoint message
      indicates that the debugger is active. It describes the breakpoint and
      previews the first line of the script, which is a function declaration.
      The command prompt also changes to indicate that the debugger has
      control.

      The preview line includes the script name and the line number of the
      previewed command.

          Entering debug mode. Use h or ? for help.

          Hit Line breakpoint on 'C:\ps-test\test.ps1:1'

          test.ps1:1   function psversion {
          DBG>

      Use the Step command (s) to execute the first statement in the script
      and to preview the next statement. The next statement uses the
      $MyInvocation automatic variable to set the value of the $ScriptName
      variable to the path and file name of the script file.

          DBG> s
          test.ps1:11  $scriptname = $MyInvocation.MyCommand.Path

      At this point, the $ScriptName variable is not populated, but you can
      verify the value of the variable by displaying its value. In this case,
      the value is $null.

          DBG> $scriptname
          DBG>

      Use another Step command (s) to execute the current statement and to
      preview the next statement in the script. The next statement calls the
      PsVersion function.

      DBG> s
      test.ps1:12  psversion

      At this point, the $ScriptName variable is populated, but you verify the
      value of the variable by displaying its value. In this case, the value
      is set to the script path.

          DBG> $scriptname
          C:\ps-test\test.ps1

      Use another Step command to execute the function call. Press ENTER,
      or type "s" for Step.

      DBG> s
      test.ps1:2       "Windows Powershell " + $psversiontable.psversion

      The debug message includes a preview of the statement in the function.
      To execute this statement and to preview the next statement in the
      function, you can use a Step command. But, in this case, use a Step-Out
      command (o). It completes the execution of the function (unless it
      reaches a breakpoint) and steps to the next statement in the script.

      DBG> o
      Windows Powershell 2.0
      Have you run a background job today (start-job)?
      test.ps1:13  "Done $scriptname"

      Because we are on the last statement in the script, the Step, Step-Out,
      and Continue commands have the same effect. In this case, use
      Step-Out (o).

      Done C:\ps-test\test.ps1
      PS C:\ps-test>

      The Step-Out command executes the last command. The standard command
      prompt indicates that the debugger has exited and returned control to the
      command processor.

      Now, run the debugger again. First, to delete the current
      breakpoint, use the Get-PsBreakpoint and Remove-PsBreakpoint cmdlets.
      (If you think you might reuse the breakpoint, use the
      Disable-PsBreakpoint cmdlet instead of Remove-PsBreakpoint.)

      PS C:\ps-test> Get-PsBreakpoint | Remove-PSBreakpoint

      You can abbreviate this command as:

      PS C:\ps-test> gbp | rbp

      Or, run the command by writing a function, such as the following
      function:

      function delbr { gbp | rbp }

      Now, create a breakpoint on the $scriptname variable.

      PS C:\ps-test> set-psbreakpoint -variable scriptname -script test.ps1

      You can abbreviate the command as:

      PS C:\ps-test> sbp -v scriptname -s test.ps1

      Now, start the script. The script reaches the variable breakpoint. The
      default mode is Write, so execution stops just before the statement
      that changes the value of the variable.

      PS C:\ps-test> .\test.ps1
      Hit Variable breakpoint on 'C:\ps-test\test.ps1:$scriptname'
          (Write access)

      test.ps1:11  $scriptname = $MyInvocation.mycommand.path
      DBG>

      Display the current value of the $scriptname variable, which
      is $null.

          DBG> $scriptname
          DBG>

      Use a Step command (s) to execute the statement that populates
      the variable. Then, display the new value of the $scriptname
      variable.

      DBG> $scriptname
      C:\ps-test\test.ps1

      Use a Step command (s) to preview the next statement in the script.

      DBG> s
      test.ps1:12  psversion

      The next statement is a call to the PsVersion function. To skip the
      function but still execute it, use a Step-Over command (v). If you are
      already in the function when you use Step-Over, it is not effective. The
      function call is displayed, but it is not executed.

      DBG> v
      Windows Powershell 2.0
      Have you run a background job today (start-job)?
      test.ps1:13  "Done $scriptname"

      The Step-Over command executes the function, and it previews the next
      statement in the script, which prints the final line.

      Use a Stop command (t) to exit the debugger. The command prompt
      reverts to the standard command prompt.

      C:\ps-test>

      To delete the breakpoints, use the Get-PsBreakpoint and
      Remove-PsBreakpoint cmdlets.

      PS C:\ps-test> Get-PsBreakpoint | Remove-PSBreakpoint

      Create a new command breakpoint on the PsVersion function.

          PS C:\ps-test> Set-PsBreakpoint -command psversion -script test.ps1

      You can abbreviate this command to:

          PS C:\ps-test> sbp -c psversion -s test.ps1

      Now, run the script.

          PS C:\ps-test> .\test.ps1
          Hit Command breakpoint on 'C:\ps-test\test.ps1:psversion'

          test.ps1:12  psversion
          DBG>

      The script reaches the breakpoint at the function call. At this point,
      the function has not yet been called. This gives you the opportunity
      to use the Action parameter of Set-PsBreakpoint to set conditions for
      the execution of the breakpoint or to perform preparatory or diagnostic
      tasks, such as starting a log or invoking a diagnostic or security
      script.

      To set an action, use a Continue command (c) to exit the script, and a
      Remove-PsBreakpoint command to delete the current breakpoint.
      (Breakpoints are read-only, so you cannot add an action to the current
      breakpoint.)

      DBG> c
      Windows PowerShell 2.0
      Have you run a background job today (start-job)?
      Done C:\ps-test\test.ps1

      PS C:\ps-test> get-psbreakpoint | remove-psbreakpoint
      PS C:\ps-test>

      Now, create a new command breakpoint with an action. The following
      command sets a command breakpoint with an action that logs the value
      of the $scriptname variable when the function is called. Because the
      Break keyword is not used in the action, execution does not stop. (The
      backtick (`) is the line-continuation character.)

         PS C:\ps-test> set-psbreakpoint -command psversion -script test.ps1  `
         -action { add-content "The value of `$scriptname is $scriptname." `
         -path action.log}

      You can also add actions that set conditions for the breakpoint. In
      the following command, the command breakpoint is executed only if the
      execution policy is set to RemoteSigned, the most restrictive policy
      that still permits you to run scripts. (The backtick (`) is the
      continuation character.)

          PS C:\ps-test> set-psbreakpoint -script test.ps1 -command psversion `
          -action { if ((get-executionpolicy) -eq "RemoteSigned") { break }}

      The Break keyword in the action directs the debugger to execute the
      breakpoint. You can also use the Continue keyword to direct the debugger
      to execute without breaking. Because the default keyword is Continue,
      you must specify Break to stop execution.

      Now, run the script.

      PS C:\ps-test> .\test.ps1
      Hit Command breakpoint on 'C:\ps-test\test.ps1:psversion'

      test.ps1:12  psversion

      Because the execution policy is set to RemoteSigned, execution stops
      at the function call.

      At this point, you might want to check the call stack. Use the
      Get-PsCallStack cmdlet or the Get-PsCallStack debugger command (k).
      The following command gets the current call stack.

      DBG> k
      2: prompt
      1: .\test.ps1: $args=[]
      0: prompt: $args=[]

      This example demonstrates just a few of the many ways to use the Windows
      PowerShell debugger.

      For more information about the debugger cmdlets, type the following
      command:

          help <cmdlet-name> -full

      For example, type:

          help set-psbreakpoint -full

SEE ALSO
    Disable-PsBreakpoint
    Get-PsBreakpoint
    Remove-PsBreakpoint
    Set-PsBreakpoint
    Set-PsDebug
    Set-Strictmode
    Write-Debug
    Write-Verbose
    Enable-PsBreakpoint
    Get-PsCallStack


about_Do

TOPIC
    about_Do

SHORT DESCRIPTION
    Runs a statement list one or more times, subject to a While or Until
    condition.

LONG DESCRIPTION
    The Do keyword works with the While keyword or the Until keyword to run
    the statements in a script block, subject to a condition. Unlike the
    related While loop, the script block in a Do loop always runs at least
    once.

    A Do-While loop is a variety of the While loop. In a Do-While loop, the
    condition is evaluated after the script block has run. As in a While loop,
    the script block is repeated as long as the condition evaluates to true.

    Like a Do-While loop, a Do-Until loop always runs at least once before
    the condition is evaluated. However, the script block runs only while
    the condition is false.

    The Continue and Break flow control keywords can be used in a Do-While
    loop or in a Do-Until loop.

  Syntax
      The following shows the syntax of the Do-While statement:

          do {<statement list>} while (<condition>)

      The following shows the syntax of the Do-Until statement:

          do {<statement list>} until (<condition>)

      The statment list contains one or more statements that run each time
      the loop is entered or repeated.

      The condition portion of the statement resolves to true or false.

  Example
      The following example of a Do statement counts the items in an
      array until it reaches an item with a value of 0.

          C:\PS> $x = 1,2,78,0
          C:\PS> do { $count++; $a++; } while ($x[$a] -ne 0)
          C:\PS> $count
          3

      The following example uses the Until keyword. Notice that
      the not equal to operator (-ne) is replaced by the
      equal to operator (-eq).

          C:\PS> $x = 1,2,78,0
          C:\PS> do { $count++; $a++; } until ($x[$a] -eq 0)
          C:\PS> $count
          3

      The following example writes all the values of an array, skipping any
      value that is less than zero.

          do
          {
              if ($x[$a] -lt 0) { continue }
              Write-Host $x[$a]
          }
          while (++$a -lt 10)

SEE ALSO
    about_While
    about_Operators
    about_Assignment_Operators
    about_Comparison_Operators
    about_Break
    about_Continue


about_Environment_Variables

TOPIC
    about_Environment_Variables

SHORT DESCRIPTION
    Describes how to access Windows environment variables in Windows
    PowerShell.

LONG DESCRIPTION
    Environment variables store information about the operating system
    environment. This information includes details such as the operating
    system path, the number of processors used by the operating system,
    and the location of temporary folders.

    The environment variables store data that is used by the operating system
    and other programs. For example, the WINDIR environment variable
    contains the location of the Windows installation directory. Programs
    can query the value of this variable to determine where Windows operating
    system files are located.

    Windows PowerShell lets you view and change Windows environment variables,
    including the variables set in the registry, and those set for a particular
    session. The Windows PowerShell environment provider simplifies this process
    by making it easy to view and change the environment variables.

    Unlike other types of variables in Windows PowerShell, environment variables
    and their values are inherited by child sessions, such as local background
    jobs and the sessions in which module members run. This makes environment
    variables well suited to storing values that are needed in both parent and
    child sessions.

  Windows PowerShell Environment Provider
      The Windows PowerShell environment provider lets you access Windows
      environment variables in Windows PowerShell in a Windows PowerShell drive
      (the Env: drive). This drive looks much like a file system drive. To go
      to the Env: drive, type:

      set-location env:

      Then, to display the contents of the Env: drive, type:

      get-childitem

      You can view the environment variables in the Env: drive from any other
      Windows PowerShell drive, and you can go into the Env: drive to view and
      change the environment variables.

  Environment Variable Objects
      In Windows PowerShell, each environment variable is represented by an
      object that is an instance of the System.Collections.DictionaryEntry
      class.

      In each DictionaryEntry object, the name of the environment variable
      is the dictionary key. The value of the variable is the dictionary
      value.

      To display an environment variable in Windows PowerShell, get an object
      that represents the variable, and then display the values of the object
      properties. When you change an environment variable in Windows
      PowerShell, use the methods that are associated with the DictionaryEntry
      object.

      To display the properties and methods of the object that represents an
      environment variable in Windows PowerShell, use the Get-Member cmdlet.
      For example, to display the methods and properties of all the objects
      in the Env: drive, type:

      get-item -path env:* | get-member

  Displaying Environment Variables
      You can use the cmdlets that contain the Item noun (the Item cmdlets) to
      display and change the values of environment variables. Because
      environment variables do not have child items, the output of Get-Item
      and Get-ChildItem is the same.

      When you refer to an environment variable, type the Env: drive name
      followed by the name of the variable. For example, to display the value
      of the COMPUTERNAME environment variable, type:

      get-childitem env:computername

      To display the values of all the environment variables, type:

      get-childitem env:

      By default, Windows PowerShell displays the environment variables in the
      order in which it retrieves them. To sort the list of environment
      variables by variable name, pipe the output of a Get-ChildItem command to
      the Sort-Object cmdlet. For example, from any Windows PowerShell drive,
      type:

      get-childitem env: | sort name

      You can also go into the Env: drive by using the Set-Location cmdlet:

      set-location env:

      When you are in the Env: drive, you can omit the Env: drive name from
      the path. For example, to display all the environment variables, type:

      get-childitem

      To display the value of the COMPUTERNAME variable from within the
      Env: drive, type:

      get-childitem computername

      You can also display and change the values of environment variables
      without using a cmdlet by using the expression parser in Windows
      PowerShell. To display the value of an environment variable, use the
      following syntax:

      $env:<variable-name>

      For example, to display the value of the WINDIR environment variable,
      type the following command at the Windows PowerShell command prompt:

      $env:windir

      In this syntax, the dollar sign ($) indicates a variable, and the drive
      name indicates an environment variable.

  Changing Environment Variables
      To make a persistent change to an environment variable, use System in
      Control Panel (Advanced tab or the Advanced System Settings item) to
      store the change in the registry.

      When you change environment variables in Windows PowerShell, the change
      affects only the current session. This behavior resembles the behavior
      of the Set command in Windows-based environments and the Setenv command
      in UNIX-based environments.

      You must also have permission to change the values of the variables. If
      you try to change a value without sufficient permission, the command
      fails, and Windows PowerShell displays an error.

      You can change the values of variables without using a cmdlet by using
      the following syntax:

          $env:<variable-name> = "<new-value>"

      For example, to append ";c:\temp" to the value of the Path
      environment variable, use the following syntax:

      $env:path = $env:path + ";c:\temp"

      You can also use the Item cmdlets, such as Set-Item, Remove-Item, and
      Copy-Item to change the values of environment variables. For example, to
      use the Set-Item cmdlet to append ";c:\temp" to the value of the Path
      environment variable, use the following syntax:

          set-item -path env:path -value ($env:path + ";c:\temp")

      In this command, the value is enclosed in parentheses so that it is
      interpreted as a unit.

  Saving Changes to Environment Variables
      To create or change the value of an environment variable in every
      Windows PowerShell session, add the change to your Windows PowerShell
      profile.

      For example, to add the C:\Temp directory to the Path environment
      variable in every Windows PowerShell session, add the following
      command to your Windows PowerShell profile.

      $env:path = $env:path + ";c:\temp"

      To add the command to an existing profile, such as the CurrentUser,AllHosts
      profile, type:

      add-content -path $profile.CurrentUserAllHosts -value '$env:path = $env:path + ";c:\temp"'

  Environment Variables That Store Preferences
      Windows PowerShell features can use environment variables to store user
      preferences. These variables work like preference variables, but they
      are inherited by child sessions of the sessions in which they are created.
      For more information about preference variables, see about_preference_variables.

      The environment variables that store preferences include:

        PSModulePath
            Stores the paths to the default module directories. Windows PowerShell
            looks for modules in the specified directories when you do not specify
            a full path to a module.

            The default value of $env:PSModulePath is:

                $home\Documents\WindowsPowerShell\Modules; $pshome\Modules

            Windows PowerShell sets the value of "$pshome\Modules" in the registry.
            It sets the value of "$home\Documents\WindowsPowerShell\Modules" each
            time you start Windows PowerShell.

            In addition, setup programs that install modules in other directories,
            such as the Program Files directory, append their locations to the
            value of PSModulePath.

            To change the default module directories, change the value of the
            PSModulePath environment variable.

            For example, to add the "C:\ps-test\Modules" directory to the value
            of the PSModulePath environment variable, type:

                $env:PSModulePath = $env:PSModulePath + ";c:\ps-test\Modules"

            The semi-colon (;) in the command separates the new path from the
            path that precedes it in the list.

            Your changes affect only the current session unless you add a
            command that changes the value to your profile or use System in
            Control Panel to change the value of the PSModulePath environment
            variable in the registry.

            For more information, see about_Modules.

SEE ALSO
    Environment (provider)


about_Escape_Characters

TOPIC
    about_Escape_Characters

SHORT DESCRIPTION
    Introduces the escape character in Windows PowerShell and explains
    its effect.

LONG DESCRIPTION
    Escape characters are used to assign a special interpretation to
    the characters that follow it.

    In Windows PowerShell, the escape character is the backtick (`), also
    called the grave accent (ASCII 96). The escape character can be used
    to indicate a literal, to indicate line continuation, and to indicate
    special characters.

  Indicating a Literal
      When an escape character precedes a variable, it prevents a value from
      being substituted for the variable. When an escape character precedes a
      double quotation mark, Windows PowerShell interprets the double quotation
      mark as a character, not as a string delimiter.

      For example:

          C:\>$a = 5
          C:\>"The value is stored in $a."
          The value is stored in 5.

          C:\>$a = 5
          C:\>"The value is stored in `$a."
          The value is stored in $a.

          C:\> "Use quotation marks (") to indicate a string."
          Unexpected token ')' in expression or statement.
          At line:1 char:25
          + "Use quotation marks (") <<<<  to indicate a string."

          C:\> "Use quotation marks (`") to indicate a string."
          Use quotation marks (") to indicate a string.

  Indicating Line Continuation
      The escape character tells Windows PowerShell that the command continues
      on the next line.

      For example:

          C:\> get-process `
          >> powershell

          Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
          -------  ------    -----      ----- -----   ------     -- -----------
              340       8    34556      31864   149     0.98   2036 powershell

  Indicating Special Characters
      When used within quotation marks, the escape character indicates a
      special character that provides instructions to the command parser.

      The following special characters are recognized by Windows PowerShell:

          `0    Null
          `a    Alert
          `b    Backspace
          `f    Form feed
          `n    New line
          `r    Carriage return
          `t    Horizontal tab
          `v    Vertical tab

      For example:

          C:\> "12345678123456781`nCol1`tColumn2`tCol3"
          12345678123456781
          Col1    Column2 Col3

      For more information, type:

          get-help about_special_characters

SEE ALSO
    about_Quoting_Rules


about_EventLogs

TOPIC
    about_EventLogs

SHORT DESCRIPTION
    Windows PowerShell creates a Windows event log that is
    named "Windows PowerShell" to record Windows PowerShell events. You can
    view this log in Event Viewer or by using cmdlets that get events, such as
    the Get-EventLog cmdlet. By default, Windows PowerShell engine and provider
    events are recorded in the event log, but you can use the event log
    preference variables to customize the event log. For example, you can add
    events about Windows PowerShell commands.

LONG DESCRIPTION
    The Windows PowerShell event log records details of Windows PowerShell
    operations, such as starting and stopping the program engine and starting
    and stopping the Windows PowerShell providers. You can also log details
    about Windows PowerShell commands.

    In Windows Vista and later versions, the Windows PowerShell event log
    is in the Application and Services Logs group. The Windows PowerShell log
    is a classic event log that does not use the Windows Eventing technology.
    To view the log, use the cmdlets designed for classic event logs, such as
    Get-EventLog.

  Viewing the Windows PowerShell Event Log

      You can view the Windows PowerShell event log in Event Viewer or by
      using the Get-EventLog and Get-WmiObject cmdlets. To view the contents
      of the Windows PowerShell log, type:

      get-eventlog -logname "Windows PowerShell"

      To examine the events and their properties, use the Sort-Object cmdlet,
      the Group-Object cmdlet, and the cmdlets that contain the Format verb
      (the Format cmdlets).

      For example, to view the events in the log grouped by the event ID, type:

      get-eventlog "Windows PowerShell" | format-table -groupby eventid

      Or, type:

      get-eventlog "Windows PowerShell" | sort-object eventid `
            | group-object eventid

      To view all the classic event logs, type:

      get-eventlog -list

      You can also use the Get-WmiObject cmdlet to use the event-related
      Windows Management Instumentation (WMI) classes to examine the event log.
      For example, to view all the properties of the event log file, type:

      get-wmiobject win32_nteventlogfile | where `
            {$_.logfilename -eq "Windows PowerShell"} | format-list -property *

      To find the Win32 event-related WMI classes, type:

    get-wmiobject -list | where {$_.name -like "win32*event*"}

      For more information, type "get-help get-eventlog" and
      "get-help get-wmiobject".

  Selecting Events for the Windows PowerShell Event Log

      You can use the event log preference variables to determine which events
      are recorded in the Windows PowerShell event log.

      There are six event log preference variables; two variables for each of
      the three logging components: the engine (the Windows PowerShell
      program), the providers, and the commands. The LifeCycleEvent variables
      log normal starting and stopping events. The Health variables log error
      events.

      The following table lists the event log preference variables.

          Variable                     Description
          --------------------------   ----------------------------------------

      $LogEngineLifeCycleEvent     Logs starting and stopping of
                                       Windows PowerShell.

      $LogEngineHealthEvent        Logs Windows PowerShell program errors.

      $LogProviderLifeCycleEvent   Logs starting and stopping of
                                       Windows PowerShell providers.

      $LogProviderHealthEvent      Logs Windows PowerShell provider errors.

      $LogCommandLifeCycleEvent    Logs starting and completion of commands.

      $LogCommandHealthEvent       Logs command errors.

      (For information about Windows PowerShell providers,
      type: "get-help about_providers".)

      By default, only the following event types are enabled:

      $LogEngineLifeCycleEvent
      $LogEngineHealthEvent
      $LogProviderLifeCycleEvent
      $LogProviderHealthEvent

      To enable an event type, set the preference variable for that event type
      to $true. For example, to enable command life-cycle events, type:

      $LogCommandLifeCycleEvent

      Or, type:

      $LogCommandLifeCycleEvent = $true

      To disable an event type, set the preference variable for that event type
      to $false. For example, to disable command life-cycle events, type:

      $LogProviderLifeCycleEvent = $false

      The variable settings apply only for the current Windows PowerShell
      session. To apply them to all Windows PowerShell sessions, add them to
      your Windows PowerShell profile.

  Security and Auditing

      The Windows PowerShell event log is designed to indicate activity and
      to provide operational details for troubleshooting.

      However, like most Windows-based application event logs, the
      Windows PowerShell event log is not designed to be secure. It should not
      be used to audit security or to record confidential or proprietary
      information.

      Event logs are designed to be read and understood by users. Users can
      read from and write to the log. A malicious user could read an event log
      on a local or remote computer, record false data, and then prevent the
      logging of their activities.

SEE ALSO
    Get-EventLog
    Get-WmiObject
    about_Preference_Variables


about_Execution_Policies

TOPIC
    about_Execution_Policies

SHORT DESCRIPTION
    Describes the Windows PowerShell execution policies and explains
    how to manage them.

LONG DESCRIPTION
    Windows PowerShell execution policies let you determine the
    conditions under which Windows PowerShell loads configuration files
    and runs scripts.

    You can set an execution policy for the local computer, for the current
    user, or for a particular session. You can also use a Group Policy
    setting to set execution policy for computers and users.

    Execution policies for the local computer and current user are stored
    in the registry. You do not need to set execution policies in your
    Windows PowerShell profile. The execution policy for a particular session
    is stored only in memory and is lost when the session is closed.

    The execution policy is not a security system that restricts user actions.
    For example, users can easily circumvent a policy by typing the script
    contents at the command line when they cannot run a script. Instead, the
    execution policy helps users to set basic rules and prevents them from
    violating them unintentionally.

 WINDOWS POWERSHELL EXECUTION POLICIES
 -------------------------------------

    The Windows PowerShell execution policies are as follows:

    "Restricted" is the default policy.

        Restricted
            - Default execution policy.

            - Permits individual commands, but will not run
              scripts.

            - Prevents running of all script files, including
              formatting and configuration files (.ps1xml), module
              script files (.psm1), and Windows PowerShell
              profiles (.ps1).

        AllSigned
            - Scripts can run.

            - Requires that all scripts and configuration files
              be signed by a trusted publisher, including scripts
              that you write on the local computer.

            - Prompts you before running scripts from publishers
              that you have not yet classified as trusted or
              untrusted.

            - Risks running unsigned scripts from sources other
              than the Internet and signed, but malicious, scripts.

        RemoteSigned
            - Scripts can run.

            - Requires a digital signature from a trusted
              publisher on scripts and configuration files that
              are downloaded from the Internet (including
              e-mail and instant messaging programs).

            - Does not require digital signatures on scripts that you have run
              and that you have written on the local computer (not
              downloaded from the Internet).

            - Risks running signed, but malicious, scripts.

        Unrestricted
            - Unsigned scripts can run. (This risks running malicious
              scripts.)

            - Warns the user before running srcipts and configuration
              files that are downloaded from the Internet.

        Bypass
            - Nothing is blocked and there are no warnings or
              prompts.

            - This execution policy is designed for configurations
              in which a Windows PowerShell script is built in to a
              a larger application or for configurations in which
              Windows PowerShell is the foundation for a program
              that has its own security model.

        Undefined
            - There is no execution policy set in the current scope.

            - If the execution policy in all scopes is Undefined, the
              effective execution policy is Restricted, which is the
              default execution policy.

    Note: On systems that do not distinguish Universal Naming Convention (UNC)
          paths from Internet paths, scripts that are identified by a UNC path
          might not be permitted to run with the RemoteSigned execution policy.

 EXECUTION POLICY SCOPE
 ----------------------
    You can set an execution policy that is effective only in a
    particular scope.

    The valid values for Scope are Process, CurrentUser, and
    LocalMachine. LocalMachine is the default when setting an
    execution policy.

    The Scope values are listed in precedence order.

        - Process
             The execution policy affects only the current session
             (the current Windows PowerShell process). The execution
             policy is stored in the $PSExecutionPolicyPreference
             environment variable. This value is deleted when the
             session in which the policy is set is closed.

        - CurrentUser
             The execution policy affects only the current user. It
             is stored in the HKEY_CURRENT_USER registry subkey.

        - LocalMachine
             The execution policy affects all users on the current
             computer. It is stored in the HKEY_LOCAL_MACHINE
             registry subkey.

    The policy that takes precedence is effective in the current
    session, even if a more restrictive policy was set at a lower
    level of precedence.

    For more information, see Set-ExecutionPolicy.

 GET YOUR EXECUTION POLICY
 ------------------------------
    To get the Windows PowerShell execution policy that is in
    effect in the current session, use the Get-ExecutionPolicy cmdlet.

    The following command gets the current execution policy:

    get-executionpolicy

    To get all of the execution policies that affect the current
    session and displays them in precedence order, type:

        get-executionpolicy -list

    The result will look similar to the following sample output:

                  Scope    ExecutionPolicy
                  -----    ---------------
          MachinePolicy          Undefined
             UserPolicy          Undefined
                Process          Undefined
            CurrentUser       RemoteSigned
           LocalMachine          AllSigned

    In this case, the effective execution policy is RemoteSigned
    because the execution policy for the current user takes precedence
    over the execution policy set for the local computer.

    To get the execution policy set for a particular scope, use the
    Scope parameter of Get-ExecutionPolicy.

    For example, the following command gets the execution policy for
    the current user scope.

        get-executionpolicy -scope CurrentUser

 CHANGE YOUR EXECUTION POLICY
 ------------------------------
    To change the Windows PowerShell execution policy on your
    computer, use the Set-ExecutionPolicy cmdlet.

    The change is effective immediately; you do not need to restart
    Windows PowerShell.

    If you set the execution policy for the local computer (the default)
    or the current user, the change is saved in the registry and remains
    effective until you change it again.

    If you set the execution policy for the current process, it is
    not saved in the registry. It is retained until the current
    process and any child processes are closed.

    Note: In Windows Vista and later versions of Windows, to run
          commands that change the execution policy for the local
          computer (the default), start Windows PowerShell with the
          "Run as administrator" option.

    To change your execution policy, type:

        Set-ExecutionPolicy <policy-name>

    For example:

        Set-ExecutionPolicy RemoteSigned

    To set the execution policy in a particular scope, type:

        Set-ExecutionPolicy <policy-name> -scope <scope>

    For example:

        Set-ExecutionPolicy RemoteSigned -scope CurrentUser

    A command to change an execution policy can succeed but
    still not change the effective execution policy.

    For example, a command that sets the execution policy for
    the local computer can succeed but be overridden by the
    execution policy for the current user.

 REMOVE YOUR EXECUTION POLICY
 ----------------------------
    To remove the execution policy for a particular scope, set
    the value of the value of the execution policy to Undefined.

    For example, to remove the execution policy for all the users of
    the local computer, type:

        set-executionpolicy Undefined

    Or, type:

        set-executionpolicy Undefined -scope LocalMachine

    If no execution policy is set in any scope, the effective
    execution policy is Restricted, which is the default.

 SET AN EXECUTION POLICY IN POWERSHELL.EXE
 -----------------------------------------
    You can use the ExecutionPolicy parameter of PowerShell.exe to
    set an execution policy for a new Windows PowerShell session.
    The policy affects only the current session and child sessions.

    To set the execution policy for a new session, start Windows PowerShell
    at the command line (such as Cmd.exe or Windows PowerShell), and then use
    the ExecutionPolicy parameter of PowerShell.exe to set the execution
    policy.

    For example:

    powershell.exe -executionpolicy -allsigned

    The execution policy that you set is not stored in the registry.
    Instead, it is stored in the $PSExecutionPolicyPreference environment
    variable. The variable is deleted when you close the session in which the
    policy is set.

    During the session, the execution policy that is set for the session takes
    precedence over an execution policy that is set in the registry for the
    local computer or current user. However, it does not take precedence over
    the execution policy set by using a Group Policy setting (discussed below).

 USE GROUP POLICY TO MANAGE EXECUTION POLICY
 -------------------------------------------
    You can use the "Turn on Script Execution" Group Policy setting
    to manage the execution policy of computers in your enterprise.
    The Group Policy setting overrides the execution policies set in Windows
    PowerShell in all scopes.

    The "Turn on Script Execution" policy settings are as follows:

    -- If you disable "Turn on Script Execution", scripts do not run.
       This is equivalent to the "Restricted" execution policy.

    -- If you enable "Turn on Script Execution", you can select an
       execution policy. The Group Policy settings are equivalent to
       the following execution policy settings.

        Group Policy                Execution Policy
        ------------                ----------------
        Allow all scripts.          Unrestricted

        Allow local scripts         RemoteSigned
        and remote signed
        scripts.

        Allow only signed           AllSigned
        scripts.

    -- If "Turn on Script Execution" is not configured, it has no
       effect. The execution policy set in Windows PowerShell is
       effective.

    The PowerShellExecutionPolicy.adm file adds the
    "Turn on Script Execution" policy to the Computer Configuration
    and User Configuration nodes in Group Policy Editor in the following
    paths.

        For Windows XP and Windows Server 2003:
        Administrative Templates\Windows Components\Windows PowerShell

        For Windows Vista and later versions of Windows:
        Administrative Templates\Classic Administrative Templates\
        Windows Components\Windows PowerShell

    Policies set in the Computer Configuration node take precedence
    over policies set in the User Configuration node.

    The PowerShellExecutionPolicy.adm file is available on the
    Microsoft Download Center. For more information, see "Administrative
    Templates for Windows PowerShell" at
    http://go.microsoft.com/fwlink/?LinkId=131786.

 EXECUTION POLICY PRECEDENCE
 ---------------------------
    When determining the effective execution policy for a
    session, Windows PowerShell evaluates the execution policies
    in the following precedence order:

        - Group Policy: Computer Configuration
        - Group Policy: User Configuration
        - Execution Policy: Process (or PowerShell.exe -ExecutionPolicy)
        - Execution Policy: CurrentUser
        - Execution Policy: LocalMachine

 MANAGE SIGNED AND UNSIGNED SCRIPTS
 ----------------------------------
    If your Windows PowerShell execution policy is RemoteSigned,
    Windows PowerShell will not run unsigned scripts that are
    downloaded from the Internet (including e-mail and instant
    messaging programs).

    You can sign the script or elect to run an unsigned script
    without changing the execution policy.

    For more information, see about_Signing.

SEE ALSO
    Get-ExecutionPolicy
    Set-ExecutionPolicy
    about_Signing
    "Administrative Templates for Windows PowerShell"
        (http://go.microsoft.com/fwlink/?LinkId=131786)


about_For

TOPIC
    about_For

SHORT DESCRIPTION
    Describes a language command you can use to run statements based on a
    conditional test.

LONG DESCRIPTION
    The For statement (also known as a For loop) is a language construct
    you can use to create a loop that runs commands in a command block while a
    specified condition evaluates to true.

    A typical use of the For loop is to iterate an array of values and to
    operate on a subset of these values. In most cases, if you want to
    iterate all the values in an array, consider using a Foreach statement.

  Syntax
      The following shows the For statement syntax.

          for (<init>; <condition>; <repeat>)
          {<statement list>}

      The <init> placeholder represents one or more commands, separated by
      commas, that are run before the loop begins. You typically use the
      <init> portion of the statement to create and initialize a variable with
      a starting value.

      This variable will then be the basis for the condition to be tested in
      the next portion of the For statement.

      The <condition> placeholder represents the portion of the For statement
      that resolves to a true or false Boolean value. Windows PowerShell
      evaluates the condition each time the For loop runs. If the statement is
      true, the commands in the command block run, and the statement is
      evaluated again. If the condition is still true, the commands in the
      statement list run again. The loop is repeated until the condition
      becomes false.

      The <repeat> placeholder represents one or more commands, separated by
      commas, that are executed each time the loop repeats. Typically, this
      is used to modify a variable that is tested inside the <condition> part
      of the statement.

      The <statement list> placeholder represents a set of one or more commands
      that are run each time the loop is entered or repeated. The contents of
      the statement list are surrounded by braces.

  Examples
      At a minimum, a For statement requires the parenthesis surrounding the
      <init>, <condition>, and <repeat> part of the statement and a command
      surrounded by braces in the <statement list> part of the statement.

      Note that the upcoming examples intentionally show code outside the
      For statement. In later examples, code is integrated into the for
      statement.

      For example, the following For statement continually displays the
      value of the $i variable until you manually break out of the command by
      pressing CTRL+C.

          $i = 1
          for (;;){Write-Host $i}

      You can add additional commands to the statement list so that
      the value of $i is incremented by 1 each time the loop is run, as the
      following example shows.

          for (;;){$i++; Write-Host $i}

      Until you break out of the command by pressing CTRL+C, this statement
      will continually display the value of the $i variable as it is
      incremented by 1 each time the loop is run.

      Rather than change the value of the variable in the statement list
      part of the For statement, you can use the <repeat> portion of the For
      statement instead, as follows.

          $i=1
          for (;;$i++){Write-Host $i}

      This statement will still repeat indefinitely until you break out of the
      command by pressing CTRL+C.

      By setting a condition (using the <condition> portion of the For
      statement), you can end the For loop when the condition evaluates to
      false. In the following example, the For loop runs while the value of
      $i is less than or equal to 10.

          $i=1
          for(;$i -le 10;$i++){Write-Host $i}

      Instead of creating and initializing the variable outside the For
      statement, you can perform this task inside the For loop by using
      the <init> portion of the For statement.

          for($i=1; $i -le 10; $i++){Write-Host $i}

      You can use carriage returns instead of semicolons to delimit the
      <init>, <condition>, and <repeat> portions of the For statement. The
      following example shows the For statement syntax in this alternative
      form.

            for (<init>
          <condition>
          <repeat>){
          <statement list>
          }

      This alternative form of the For statement works in Windows PowerShell
      script files and at the Windows PowerShell command prompt. However, it
      is easier to use the For statement syntax with semicolons when you enter
      interactive commands at the command prompt.

      The For loop is more flexible than the Foreach loop because it allows
      you to increment values in an array or collection by using patterns. In
      the following example, the $i variable is incremented by 2 in the
      <repeat> portion of the for statement.

          for ($i = 0; $i -ile 20; $i += 2) {Write-Host $i}

SEE ALSO
    about_Comparison_Operators
    about_Foreach


about_Foreach

TOPIC
    about_Foreach

SHORT DESCRIPTION
    Describes a language command you can use to traverse all the items in a
    collection of items.

LONG DESCRIPTION
    The Foreach statement (also known as a Foreach loop) is a language
    construct for stepping through (iterating) a series of values in a
    collection of items.

    The simplest and most typical type of collection to traverse is an array.
    Within a Foreach loop, it is common to run one or more commands against
    each item in an array.

  Syntax
      The following shows the Foreach syntax:

          foreach ($<item> in $<collection>){<statement list>}

  The Foreach Statement Outside a Command Pipeline
      The part of the Foreach statement enclosed in parenthesis represents a
      variable and a collection to iterate. Windows PowerShell creates the
      variable ($<item>) automatically when the Foreach loop runs. Prior to
      each iteration through the loop, the variable is set to a value in the
      collection. The block following a Foreach statement {<statement list>}
      contains a set of commands to execute against each item in a collection.

  Examples
      For example, the Foreach loop in the following example displays the
      values in the $letterArray array.

          $letterArray = "a","b","c","d"
          foreach ($letter in $letterArray)
          {
              Write-Host $letter
          }

      In this example, the $letterArray array is created and initialized with
      the string values "a", "b", "c", and "d". The first time the Foreach
      statement runs, it sets the $letter variable equal to the first item in
      $letterArray ("a"). Then, it uses the Write-Host cmdlet to display the
      letter a. The next time through the loop, $letter is set to "b", and so
      on. After the Foreach loop displays the letter d, Windows PowerShell
      exits the loop.

      The entire Foreach statement must appear on a single line to run it as a
      command at the Windows PowerShell command prompt. The entire Foreach
      statement does not have to appear on a single line if you place the
      command in a .ps1 script file instead.

      Foreach statements can also be used together with cmdlets that
      return a collection of items. In the following example, the Foreach
      statement steps through the list of items that is returned by the
      Get-ChildItem cmdlet.

          foreach ($file in Get-ChildItem)
          {
              Write-Host $file
          }

      You can refine the example by using an If statement to limit the results
      that are returned. In the following example, the Foreach statement
      performs the same looping operation as the previous example, but it adds
      an If statement to limit the results to files that are greater than 100
      kilobytes (KB):

          foreach ($file in Get-ChildItem)
          {
              if ($file.length -gt 100k)
              {
                  Write-Host $file
              }
          }

      In this example, the Foreach loop uses a property of the $file variable
      to perform a comparison operation ($file.length -gt 100k). The $file
      variable contains all the properties in the object that is returned by
      the Get-ChildItem cmdlet. Therefore, you can return more than just a
      file name. In the next example, Windows PowerShell returns the length and
      the last access time inside the statement list:

          foreach ($file in Get-ChildItem)
          {
              if ($file.length -gt 100k)
              {
                  Write-Host $file
                  Write-Host $file.length
                  Write-Host $file.lastaccesstime
              }
          }

      In this example, you are not limited to running a single command in a
      statement list.

      You can also use a variable outside a Foreach loop and increment the
      variable inside the loop. The following example counts files over 100 KB
      in size:

          $i = 0
          foreach ($file in Get-ChildItem)
          {
              if ($file.length -gt 100k)
              {
                  Write-Host $file "file size:" ($file.length /
          1024).ToString("F0") KB
                  $i = $i + 1
              }
          }

          if ($i -ne 0)
          {
              Write-Host
              Write-Host $i " file(s) over 100 KB in the current
          directory."}
          else
          {
              Write-Host "No files greater than 100 KB in the current
          directory."
          }

      In the preceding example, the $i variable is set to 0 outside the loop,
      and the variable is incremented inside the loop for each file that is
      found that is larger than 100 KB. When the loop exits, an If statement
      evaluates the value of $i to display a count of all the files over
      100 KB. Or, it displays a message stating that no files over 100 KB were
      found.

      The previous example also demonstrates how to format the file length
      results:

          ($file.length / 1024).ToString("F0")

      The value is divided by 1,024 to show the results in kilobytes rather
      than bytes, and the resulting value is then formatted using the
      fixed-point format specifier to remove any decimal values from the
      result. The 0 makes the format specifier show no decimal places.

  The Foreach Statement Inside a Command Pipeline
      When Foreach appears in a command pipeline, Windows PowerShell uses the
      foreach alias, which calls the ForEach-Object command. When you use
      the foreach alias in a command pipeline, you do not include
      the ($<item> in $<collection>) syntax as you do with the Foreach
      statement. This is because the prior command in the pipeline provides
      this information. The syntax of the foreach alias when used in a command
      pipeline is as follows:

          <command> | foreach {<command_block>}

      For example, the Foreach loop in the following command pipeline displays
      any processes whose working set (memory usage) is greater
      than 20 megabytes (MB). Windows PowerShell pipes the output from the
      Get-Process command to the foreach alias. Inside the foreach alias
      command block, the $_.WS variable contains the value of the WS (working
      set) property passed to it by the Get-Process cmdlet. (The $_ portion
      of the declaration is a Windows Script Host [WSH] automatic variable,
      and the WS portion is a property). The If statement uses a conditional
      statement to determine whether the working set is greater than 20 MB
      (20,000,000 bytes). If so, the name of the process that is stored in
      the $_.name variable and the working-set size in megabytes are displayed.
      If no process working set is over 20 MB, nothing is displayed.

          Write-Host "Processes with working-sets greater than 20 MB"
          Get-Process | foreach {
              if ($_.WS -gt 20m)
              {
                  Write-Host $_.name ": "
          ($_.WS/1m).ToString("F0") MB -Separator ""
              }
          }

      The foreach alias also supports beginning command blocks, middle command
      blocks, and end command blocks. The beginning and end command blocks run
      once, and the middle command block runs every time the Foreach loop steps
      through a collection or array.

      The syntax of the foreach alias when used in a command pipeline with a
      beginning, middle, and ending set of command blocks is as follows:

          <command> | foreach {<beginning command_block>}{<middle
          command_block>}{<ending command_block>}

      The following example demonstrates the use of the beginning, middle, and
      end command blocks.

          Get-ChildItem | foreach {
          $fileCount = $directoryCount = 0}{
          if ($_.PsIsContainer) {$directoryCount++} else {$fileCount++}}{
          "$directoryCount directories and $fileCount files"}

      The beginning block creates and initializes two variables to 0:

          {$fileCount = $directoryCount = 0}

      The middle block evaluates whether each item returned by Get-ChildItem
      is a directory or a file:

          {if ($_.PsIsContainer) {$directoryCount++} else {$fileCount++}}

      If the item that is returned is a directory, the $directoryCount
      variable is incremented by 1. If the item is not a directory,
      the $fileCount variable is incremented by 1. The ending block runs after
      the middle block completes its looping operation and then returns the
      results of the operation:

          {"$directoryCount directories and $fileCount files"}

      By using the beginning, middle, and ending command block structure and
      the pipeline operator, you can rewrite the earlier example to find any
      files that are greater than 100 KB, as follows:

          Get-ChildItem | foreach{
              $i = 0}{
              if ($_.length -gt 100k)
              {
                  Write-Host $_.name "file size:" ($_.length /
          1024).ToString("F0") KB
                  $i++
              }
              }{
              if ($i -ne 0)
              {
                  Write-Host
                  Write-Host "$i file(s) over 100 KB in the current
          directory."
              }
              else
              {
              Write-Host "No files greater than 100 KB in the current
          directory."}
              }

SEE ALSO
    about_Automatic_Variables
    about_If
    Foreach-Object


about_Format.ps1xml

TOPIC
    about_Format.ps1xml

SHORT DESCRIPTION
    The Format.ps1xml files in Windows PowerShell define the default display
    of objects in the Windows PowerShell console. You can create your own
    Format.ps1xml files to change the display of objects or to define default
    displays for new object types that you create in Windows PowerShell.

LONG DESCRIPTION
    The Format.ps1xml files in Windows PowerShell define the default display
    of objects in Windows PowerShell. You can create your own Format.ps1xml
    files to change the display of objects or to define default displays
    for new object types that you create in Windows PowerShell.

    When Windows PowerShell displays an object, it uses the data in structured
    formatting files to determine the default display of the object. The
    data in the formatting files determines whether the object is rendered in
    a table or in a list, and it determines which properties are displayed by
    default.

    The formatting affects the display only. It does not affect which object
    properties are passed down the pipeline or how they are passed.

    Windows PowerShell includes seven formatting files. These files are
    located in the installation directory ($pshome). Each file defines the
    display of a group of Microsoft .NET Framework objects:

    Certificate.Format.ps1xml
            Objects in the Certificate store, such as X.509 certificates and
            certificate stores.

    DotNetTypes.Format.ps1xml
            Other .NET Framework types, such as CultureInfo, FileVersionInfo,
            and EventLogEntry objects.

    FileSystem.Format.ps1xml
            File system objects, such as files and directories.

    Help.Format.ps1xml
            Help views, such as detailed and full views, parameters, and
            examples.

    PowerShellCore.format.ps1xml
            Objects generated by Windows PowerShell core cmdlets, such as
            Get-Member and Get-History.

    PowerShellTrace.format.ps1xml
            Trace objects, such as those generated by the Trace-Command cmdlet.

    Registry.format.ps1xml
            Registry objects, such as keys and entries.

    A formatting file can define four different views of each object:
    table, list, wide, and complex. For example, when the output of a
    Get-ChildItem command is piped to a Format-List command, Format-List
    uses the view in the FileSystem.format.ps1xml file to determine how to
    display the file and folder objects as a list.

    In a Format.ps1xml file, a view is defined by a set of XML tags that
    describe the name of the view, the type of object to which it can
    be applied, the column headers, and the properties that are displayed
    in the body of the view. The format in Format.ps1xml files is applied
    just before the data is presented to the user.

  Creating New Format.ps1xml Files

      The .ps1xml files that are installed with Windows PowerShell are
      digitally signed to prevent tampering because the formatting can include
      script blocks. Therefore, to change the display format of an existing
      object view, or to add views for new objects, create your own
      Format.ps1xml files, and then add them to your Windows PowerShell
      session.

      To create a new file, copy an existing Format.ps1xml file. The new file
      can have any name, but it must have a .ps1xml file name extension. You
      can place the new file in any directory that is accessible to Windows
      PowerShell, but it is useful to place the files in the Windows PowerShell
      installation directory ($pshome) or in a subdirectory of the installation
      directory.

      To change the formatting of a current view, locate the view in the
      formatting file, and then use the tags to change the view. To create a
      view for a new object type, create a new view, or use an existing view
      as a model. (The tags are described in the next section of this topic.)
      You can then delete all the other views in the file so that the changes
      are obvious to anyone examining the file.

      When you have saved the changes, use the Update-FormatData cmdlet to add
      the new file to your Windows PowerShell session. If you want your view
      to take precedence over a view defined in the built-in files, use the
      PrependData parameter of Update-FormatData. Update-FormatData affects
      only the current session. To make the change to all future sessions, add
      the Update-FormatData command to your Windows PowerShell profile.

  Example: Adding Calendar Data to Culture Objects

      This example shows how to change the formatting of the culture objects
      (System.Globalization.CultureInfo) generated by the Get-Culture cmdlet.
      The commands in the example add the calendar property to the default
      table view display of culture objects.

      The first step is to find the Format.ps1xml file that contains the
      current view of the culture objects. The following Select-String command
      finds the file:

      select-string -path $pshome\*format.ps1xml `
              -pattern System.Globalization.CultureInfo

      This command reveals that the definition is in the
      DotNetTypes.Format.ps1xml file.

      The next command copies the file contents to a new file,
      MyDotNetTypes.Format.ps1xml.

      copy-item DotNetTypes.Format.ps1xml MyDotNetTypes.Format.ps1xml

      Next, open the MyDotNetTypes.Format.ps1xml file in any XML or text
      editor, such as Notepad. Find the System.Globalization.CultureInfo object
      section. The following XML defines the views of the CultureInfo object.
      The object has only a TableControl view.

      <View>
          <Name>System.Globalization.CultureInfo</Name>
          <ViewSelectedBy>
             <TypeName>Deserialized.System.Globalization.CultureInfo</TypeName>
             <TypeName>System.Globalization.CultureInfo</TypeName>
          </ViewSelectedBy>

          <TableControl>
              <TableHeaders>
                  <TableColumnHeader>
                      <Width>16</Width>
                  </TableColumnHeader>
                  <TableColumnHeader>
                      <Width>16</Width>
                  </TableColumnHeader>
                  <TableColumnHeader/>
              </TableHeaders>
              <TableRowEntries>
                  <TableRowEntry>
                      <TableColumnItems>
                          <TableColumnItem>
                              <PropertyName>LCID</PropertyName>
                          </TableColumnItem>
                          <TableColumnItem>
                              <PropertyName>Name</PropertyName>
                          </TableColumnItem>
                          <TableColumnItem>
                              <PropertyName>DisplayName</PropertyName>
                          </TableColumnItem>
                      </TableColumnItems>
                  </TableRowEntry>
               </TableRowEntries>
          </TableControl>
      </View>

      Delete the remainder of the file, except for the opening <?XML>,
      <Configuration>, and <ViewDefinitions> tags and the closing
      <ViewDefintions> and <Configuration> tags. You must also delete the
      digital signature whenever you change the file.

      <?xml version="1.0" encoding="utf-8" ?>
      <Configuration>
          <ViewDefinitions>
              <View>
                  <Name>System.Globalization.CultureInfo</Name>
                  <ViewSelectedBy>
                      <TypeName>Deserialized.System.Globalization.CultureInfo</TypeName>
                      <TypeName>System.Globalization.CultureInfo</TypeName>
                  </ViewSelectedBy>

                  <TableControl>
                      <TableHeaders>
                          <TableColumnHeader>
                              <Width>16</Width>
                          </TableColumnHeader>
                          <TableColumnHeader>
                              <Width>16</Width>
                          </TableColumnHeader>
                          <TableColumnHeader/>
                      </TableHeaders>
                      <TableRowEntries>
                          <TableRowEntry>
                              <TableColumnItems>
                                  <TableColumnItem>
                                      <PropertyName>LCID</PropertyName>
                                  </TableColumnItem>
                                  <TableColumnItem>
                                      <PropertyName>Name</PropertyName>
                                  </TableColumnItem>
                                  <TableColumnItem>
                                      <PropertyName>DisplayName</PropertyName>
                                  </TableColumnItem>
                              </TableColumnItems>
                          </TableRowEntry>
                       </TableRowEntries>
                  </TableControl>
              </View>
          </ViewDefinitions>
      </Configuration>

      Next, create a new column for the Calendar property by adding a new set
      of <TableColumnHeader> tags. The value of the Calendar property can be
      long, so a value of 45 characters is used, as follows:

                <TableControl>
                    <TableHeaders>
                        <TableColumnHeader>
                            <Width>16</Width>
                        </TableColumnHeader>
                        <TableColumnHeader>
                            <Width>16</Width>
                        </TableColumnHeader>

                        <TableColumnHeader>
                            <Width>45</Width>
                        </TableColumnHeader>

                        <TableColumnHeader/>
                    </TableHeaders>

      Now, add a new column item in the table rows, as follows:

                <TableRowEntries>
                    <TableRowEntry>
                        <TableColumnItems>
                            <TableColumnItem>
                                <PropertyName>LCID</PropertyName>
                            </TableColumnItem>
                            <TableColumnItem>
                                <PropertyName>Name</PropertyName>
                            </TableColumnItem>

                            <TableColumnItem>
                                <PropertyName>Calendar</PropertyName>
                            </TableColumnItem>

                            <TableColumnItem>
                                <PropertyName>DisplayName</PropertyName>
                            </TableColumnItem>
                        </TableColumnItems>
                    </TableRowEntry>
                 </TableRowEntries>

      After saving the file and closing it, use an Update-FormatData command,
      such as the following command, to add the new format file to the current
      session. The command uses the PrependData parameter to place the new file
      in a higher precedence order than the original file. (For more
      information about Update-FormatData, type "get-help update-formatdata".)

      update-formatdata -prependpath $pshome\MyDotNetTypes.format.ps1xml

      To test the change, type "get-culture", and then review the output,
      which includes the Calendar property.

      C:\PS> get-culture

      LCID Name  Calendar                               DisplayName
      ---- ----  --------                               -----------
      1033 en-US System.Globalization.GregorianCalendar English (United States)

  The XML in Format.ps1xml Files

      The ViewDefinitions section of each Format.ps1xml file contains the
      <View> tags that define each view. A typical <View> tag includes the
      following tags:

          <Name>
              The <Name> tag identifies the name of the view.

          <ViewSelectedBy>
              The <ViewSelectedBy> tag specifies the object type or types to
              which the view applies.

          <GroupBy>
              The <GroupBy> tag specifies how items in the view will be
              combined in groups.

          <TableControl>
          <ListControl>
          <WideControl>
          <ComplexControl>
              These tags contain the tags that specify how each item will be
              displayed.

      The <ViewSelectedBy> tag can contain a <TypeName> tag for each object
      type to which the view applies. Or, it can contain a <SelectionSetName>
      tag that references a selection set that is defined elsewhere by using
      a <SelectionSet> tag.

      The <GroupBy> tag contains a <PropertyName> tag that specifies the
      object property by which items are to be grouped. It also contains either
      a <Label> tag that specifies a string to be used as a label for each
      group or a <ComplexControlName> tag that references a complex control
      defined elsewhere using a <Control> tag. The <Control> tag contains a
      <Name> tag and a <ComplexControl> tag.

      The <TableControl> tag typically contains <TableHeaders> and
      <TableRowEntries> tags that define the formatting for the table's heads
      and rows. The <TableHeaders> tag typically contains <TableColumnHeader>
      tags that contain <Label>, <Width>, and <Alignment> tags. The
      <TableRowEntries> tag contains <TableRowEntry> tags for each row in the
      table. The <TableRowEntry> tag contains a <TableColumnItems> tag
      that contains a <TableColumnItem> tag for each column in the row.
      Typically, the <TableColumnItem> tag contains either a <PropertyName> tag
      that identifies the object property to be displayed in the defined
      location, or a <ScriptBlock> tag that contains script code that
      calculates a result that is to be displayed in the location.

      Note: Script blocks can also be used elsewhere in locations where
            calculated results can be useful.

      The <TableColumnItem> tag can also contain a <FormatString> tag that
      specifies how the property or the calculated results will be displayed.

      The <ListControl> tag typically contains a <ListEntries> tag. The
      <ListEntries> tag contains a <ListItems> tag. The <ListItems> tag
      contains <ListItem> tags, which contain <PropertyName> tags.
      The <PropertyName> tags specify the object property to be displayed at
      the specified location in the list. If the view selection is defined
      using a selection set, the <ListControl> tag can also contain an
      <EntrySelectedBy> tag that contains one or more <TypeName> tags. These
      <TypeName> tags specify the object type that the <ListControl> tag is
      intended to display.

      The <WideControl> tag typically contains a <WideEntries> tag. The
      <WideEntries> tag contains one or more <WideEntry> tags. A <WideEntry>
      tag typically contains a <PropertyName> tag that specifies the property
      to be displayed at the specified location in the view. The <PropertyName>
      tag can contain a <FormatString> tag that specifies how the property is
      to be displayed.

      The <ComplexControl> tag contains more complex combinations of tags than
      other view types. A <ComplexControl> tag typically contains
      a <ComplexEntries> tag. A <ComplexEntries> tag contains multiple
      <ComplexEntry> tags. A <ComplexEntry> tag typically contains a
      <ComplexItem> tag. This tag, in turn, can contain a variety of tags that
      specify contents and formatting for the specified location in the view,
      including <Text>, <Indentation>, <ExpressionBinding>, and <NewLine> tags.

  Update-FormatData

      To load your Format.ps1xml files into a Windows PowerShell session, use
      the Update-FormatData cmdlet. If you want the views in your file to
      take precedence over the views in the built-in Format.ps1xml file, use
      the PrependData parameter of Update-FormatData. Update-FormatData affects
      only the current session. To make the change to all future sessions, add
      the Update-FormatData command to your Windows PowerShell profile.

  Default Displays in Types.ps1xml

      The default displays of some basic object types are defined in the
      Types.ps1xml file in the $pshome directory. The nodes are named
      PsStandardMembers, and the subnodes use one of the following tags:

          <DefaultDisplayProperty>
          <DefaultDisplayPropertySet>
          <DefaultKeyPropertySet>

      For more information, type the following command:

      get-help about_types.ps1xml

  Tracing Format.ps1xml File Use

      To detect errors in the loading or application of Format.ps1xml files,
      use the Trace-Command cmdlet with any of the following format
      components as the value of the Name parameter:

      FormatFileLoading
          UpdateFormatData
          FormatViewBinding

      For more information, type the following commands:

          get-help trace-command
          get-help get-tracesource

  Signing a Format.ps1xml File

      To protect the users of your Format.ps1xml file, sign the file using
      a digital signature. For more information, type:

          get-help about_signing

SEE ALSO
    Update-FormatData
    Trace-Command
    Get-TraceSource


about_Functions

TOPIC
    about_Functions

SHORT DESCRIPTION
    Describes how to create and use functions in Windows PowerShell.

LONG DESCRIPTION
    A function is a list of statements that has a name that you assign. When
    you run a function, you type the function name. The statements in the list
    run as if you had typed them at the command prompt.

    Like cmdlets, functions can have parameters. The parameters can be named,
    positional, switch, or dynamic parameters. Function parameters can be read
    from the command line or from the pipeline.

    Functions can return values that can be displayed, assigned to variables,
    or passed to other functions or cmdlets.

    The function's statement list can contain different types of statement
    lists with the keywords Begin, Process, and End. These statement lists
    handle input from the pipeline differently.

    A filter is a special kind of function that uses the Filter keyword.

    Functions can also act like cmdlets. You can create a function that works
    just like a cmdlet without using C# programming. For more information,
    see about_Functions_Advanced.

  Syntax
      The following is the syntax for a function:

          function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]
          {
              param([type]$parameter1 [,[type]$parameter2])

              dynamicparam {<statement list>}

              begin {<statement list>}
              process {<statement list>}
              end {<statement list>}
          }

      A function includes the following items:

          - A Function keyword
          - A scope (optional)
          - A name that you select
          - Any number of named parameters (optional)
          - One or more Windows PowerShell commands enclosed in braces ({})

      For more information about the Dynamicparam keyword and dynamic
      parameters in functions, see about_Functions_Advanced_Parameters.

  Simple Functions
      Functions do not have to be complicated to be useful. The following
      function gets the environment variables that do not belong to the System
      account of the current system:

          function other_env
          {
             get-wmiObject win32_environment |
                where {$_.username -ne "<System>"}
          }

      To run the function, type "other_env".

      You can create a toolbox of useful small functions. Add these functions
      to your Windows PowerShell profile, as described in about_Profiles and
      later in this topic.

  Functions with Parameters
      You can use parameters with functions, including named parameters,
      positional parameters, switch parameters, and dynamic parameters. For
      more information about dynamic parameters in functions,
      see about_Functions_Advanced_Parameters.

  Named Parameters
      You can define any number of named parameters. You can include a default
      value for named parameters, as described later in this topic.

      You can define parameters inside the braces using the Param keyword, as
      shown in the following sample syntax:

          function <name> {
               param ([type]$parameter1[,[type]$parameter2])
               <statement list>
          }

      You can also define parameters outside the braces without the Param
      keyword, as shown in the following sample syntax:

          function <name> [([type]$parameter1[,[type]$parameter2])] {
              <statement list>
          }

      There is no difference between these two methods. Use the method that
      you prefer.

      When you run the function, the value you supply for a parameter is
      assigned to a variable that contains the parameter name. The value of
      that variable can be used in the function.

      The following example is a function called Small_files. This function
      has a $size parameter. The function displays all the files that are
      smaller than the value of the $size parameter, and it excludes
      directories:

          function small_files {
              param ($size)
              Get-ChildItem c:\ | where {
                  $_.length -lt $size -and !$_.PSIsContainer}
          }

      In the function, you can use the $size variable, which is the name
      defined for the parameter.

      To use this function, type the following command:

          C:\PS> function small_files –size 50

      You can also enter a value for a named parameter without the parameter
      name. For example, the following command gives the same result as a
      command that names the Size parameter:

          C:\PS> function small_files 50

      To define a default value for a parameter, type an equal sign and the
      value after the parameter name, as shown in the following variation of
      the Small_files example:

          function small_files ($size = 100) {
              Get-ChildItem c:\ | where {
                  $_.length -lt $size -and !$_.PSIsContainer}
          }

      If you type "small_files" without a value, the function assigns 100 to
      $size. If you provide a value, the function uses that value.

  Positional Parameters
      A positional parameter is a parameter without a parameter name. Windows
      PowerShell uses the parameter value order to associate each parameter
      value with a parameter in the function.

      When you use positional parameters, type one or more values after the
      function name. Positional parameter values are assigned to the $args
      array variable. The value that follows the function name is assigned to
      the first position in the $args array, $args[0].

      The following Extension function adds the .txt file name extension to a
      file name that you supply:

          function extension {
              $name = $args[0] + ".txt"
              $name
          }

          C:\PS> extension myTextFile
          myTextFile.txt

      Functions can take more than one positional parameter. The following
      example displays any values entered with the function name.

          function repeat { foreach ($arg in $args) { "The input is $arg" } }

          C:\PS>repeat one
          The input is one

          C:\PS> repeat one two three
          The input is one
          The input is two
          The input is three

      This function can be used with any number of values. The function
      assigns each value to a position in the $args array.

  Switch Parameters
      A switch is a parameter that does not require a value. Instead, you type
      the function name followed by the name of the switch parameter.

      To define a switch parameter, specify the type [switch] before the
      parameter name, as shown in the following example:

          function switchExample {
              param ([switch]$on)
              if ($on) { "Switch on" }
              else { "Switch off" }
          }

      When you type the On switch parameter after the function name, the
      function displays "Switch on". Without the switch parameter, it displays
      "Switch off".

          C:\PS> SwitchExample -on
          Switch on

          C:\PS> SwitchExample
          Switch off

      You can also assign a Boolean value to a switch when you run the
      function, as shown in the following example:

          C:\PS> SwitchExample -on:$true
          Switch on

          C:\PS> SwitchExample -on:$false
          Switch off

  Piping Objects to Functions
      Any function can take input from the pipeline. You can control how a
      function processes input from the pipeline using Begin, Process, and End
      keywords. The following sample syntax shows the three keywords:

          function <name> {
              begin {<statement list>}
              process {<statement list>}
              end {<statement list>}
          }

      The Begin statement list runs one time only, at the beginning of
      the function.

      The Process statement list runs one time for each object in the pipeline.
      While the Process block is running, each pipeline object is assigned to
      the $_ automatic variable, one pipeline object at a time.

      After the function receives all the objects in the pipeline, the End
      statement list runs one time. If no Begin, Process, or End keywords are
      used, all the statements are treated like an End statement list.

      The following function uses the Process keyword. The function displays
      examples from the pipeline:

          function pipelineFunction
          {
              process {"The value is: $_"}
          }

      To demonstrate this function, enter an array of numbers created with
      commas, as shown in the following example:

          C:\PS> 1,2,4 | pipelineFunction
          The value is: 1
          The value is: 2
          The value is: 4

      When you use a function in a pipeline, the objects piped to the function
      are assigned to the $input automatic variable. The function runs
      statements with the Begin keyword before any objects come from the
      pipeline. The function runs statements with the End keyword after all
      the objects have been received from the pipeline.

      The following example shows the $input automatic variable with Begin and
      End keywords.

          function PipelineBeginEnd
          {
              begin {"Begin: The input is $input"}
              end {"End:   The input is $input" }
          }

      If this function is run by using the pipeline, it displays the following
      results:

          C:\PS> 1,2,4 | PipelineBeginEnd
          Begin: The input is
          End:   The input is 1 2 4

      When the Begin statement runs, the function does not have the input from
      the pipeline. The End statement runs after the function has the values.

      If the function has a Process keyword, the function reads the data in
      $input. The following example has a Process statement list:

          function PipelineInput
          {
              process {"Processing:  $_ " }
              end {"End:   The input is: $input" }
          }

      In this example, each object that is piped to the function is sent to the
      Process statement list. The Process statements run on each object, one
      object at a time. The $input automatic variable is empty when the
      function reaches the End keyword.

          C:\PS> 1,2,4 | PipelineInput
          Processing:  1
          Processing:  2
          Processing:  4
          End:   The input is:

  Filters
      A filter is a type of function that runs on each object in the pipeline.
      A filter resembles a function with all its statements in a Process block.

      The syntax of a filter is as follows:

          filter [<scope:>]<name> {<statement list>}

      The following filter takes log entries from the pipeline and then
      displays either the whole entry or only the message portion of the entry:

          filter ErrorLog ([switch]$message)
          {
              if ($message) { out-host -inputobject $_.Message }
              else { $_ }
          }

  Function Scope
      A function exists in the scope in which it was created.

      If a function is part of a script, the function is available to
      statements within that script. By default, a function in a script is not
      available at the command prompt.

      You can specify the scope of a function. For example, the function is
      added to the global scope in the following example:

          function global:get-dependentsvs { get-service |
             where {$_.dependentservices} }

      When a function is in the global scope, you can use the function in
      scripts, in functions, and at the command line.

      Functions normally create a scope. The items created in a function, such
      as variables, exist only in the function scope.

      For more information about scope in Windows PowerShell, see about_Scope.

  Finding and Managing Functions Using the Function: Drive
      All the functions and filters in Windows PowerShell are automatically
      stored in the Function: drive. This drive is exposed by the Windows
      PowerShell Function provider.

      When referring to the Function: drive, type a colon after Function, just
      as you would do when referencing the C or D drive of a computer.

      The following command displays all the functions in the current session
      of Windows PowerShell:

          C:\PS>    dir function:

      The commands in the function are stored as a script block in the
      definition property of the function. For example, to display the
      commands in the Help function that comes with Windows PowerShell, type:

          (dir function:help).definition

      For more information about the Function: drive, see Function.

  Reusing Functions in New Sessions
      When you type a function at the Windows PowerShell command prompt, the
      function becomes part of the current session. It is available until the
      session ends.

      To use your function in all Windows PowerShell sessions, add the function
      to your Windows PowerShell profile. For more information about profiles,
      see about_Profiles.

      You can also save your function in a Windows PowerShell script file.
      Type your function in a text file, and then save the file with the .ps1
      file name extension.

  Writing Help for Functions
    The Get-Help cmdlet gets help for functions, as well as for cmdlets,
    providers, and scripts. To get help for a function, type Get-Help followed
    by the function name.

    For example, to get help for the MyDisks function, type:

        get-help MyDisks

    You can write help for a function by using either of the two following methods:

    --  Comment-Based Help  for Functions

        Create a help topic by using special keywords in the comments. To create
        comment-based help for a function, the comments must be placed at the
        beginning or end of the function body or on the lines preceding the function
        keyword. For more information about comment-based help, see
        about_Comment_Based_Help.

    --  XML-Based Help  for Functions

        Create an XML-based help topic, such as the type that is typically
        created for cmdlets. XML-based help is required if you are localizing
        help topics into multiple languages.

        To associate the function with the XML-based help topic, use the
        .ExternalHelp help comment keyword. For more information about the
        ExternalHelp keyword, see about_Comment_Based_Help. For more information
        about XML-based help, see "How to Write Cmdlet Help" in MSDN.

SEE ALSO
    about_Automatic_Variables
    about_Comment_Based_Help
    about_Functions_Advanced
    about_Functions_CmdletBindingAttribute
    about_Parameters
    about_Profiles
    about_Scopes
    about_Script_Blocks
    Function (provider)


about_Functions_Advanced

TOPIC
    about_Functions_Advanced

SHORT DESCRIPTION
    Introduces advanced functions that act similar to cmdlets.

LONG DESCRIPTION
    Advanced functions allow you to write functions that can perform operations
    that are similar to the operations you can perform with cmdlets. Advanced
    functions are helpful when you want to quickly write a function without
    having to write a compiled cmdlet using a Microsoft .NET Framework
    language. These functions are also helpful when you want to restrict the
    functionality of a compiled cmdlet or when you want to write a function
    that is similar to a compiled cmdlet.

    There is a difference between authoring a compiled cmdlet and an advanced
    function. Compiled cmdlets are .NET Framework classes that must be written
    in a .NET Framework language such as C#. In contrast, advanced functions
    are written in the Windows PowerShell script language in the same way that
    other functions or script blocks are written.

    Advanced functions use the CmdletBinding attribute to identify them as
    functions that act similar to cmdlets. The CmdletBinding attribute is
    similar to the Cmdlet attribute that is used in compiled cmdlet classes to
    identify the class as a cmdlet. For more information about this attribute,
    see about_Functions_CmdletBindingAttribute.

    The following example shows a function that accepts a name and then prints
    a greeting using the supplied name. Also notice that this function defines
    a name that includes a verb (Send) and noun (Greeting) pair similar to the
    verb-noun pair of a compiled cmdlet. However, functions are not required
    to have a verb-noun name.

        function Send-Greeting
        {
          [CmdletBinding()]
          Param(
              [Parameter(Mandatory=$true)]
              [string] $Name
          )
          Process
          {
            write-host ("Hello " + $Name + "!")
          }
        }

    The parameters of the function are declared by using the Parameter
    attribute. This attribute can be used alone, or it can be combined with
    the Alias attribute or with several other parameter validation attributes.
    For more information about how to declare parameters (including dynamic
    parameters that are added at runtime), see
    about_Functions_Advanced_Parameters.

    The actual work of the previous function is performed in the Process
    block, which is equivalent to the ProcessingRecord method that is used by
    compiled cmdlets to process the data that is passed to the cmdlet. This
    block, along with the Begin and End blocks, is described in the
    about_Functions_Advanced_Methods topic.

    Advanced functions differ from compiled cmdlets in the following ways:

        - Advanced function parameter binding does not throw an exception when
          an array of strings is bound to a Boolean parameter.

        - The ValidateSet attribute and the ValidatePattern attribute cannot
          pass named parameters.

        - Advanced functions cannot be used in transactions.

SEE ALSO
    about_Functions_Advanced_CmdletBindingAttribute
    about_Functions_Advanced_Methods
    about_Functions_Advanced_Parameters
    Windows PowerShell Cmdlets (http://go.microsoft.com/fwlink/?LinkID=135279)


about_Functions_Advanced_Methods

TOPIC
    about_Functions_Advanced_Methods

SHORT DESCRIPTION
    Describes how functions that specify the CmdletBinding attribute can use
    the methods and properties that are available to compiled cmdlets.

LONG DESCRIPTION
    Functions that specify the CmdletBinding attribute can access a number of
    methods and properties through the $pscmdlet variable. These methods
    include the following methods:

        - Input-processing methods that compiled cmdlets use to do their work.

        - The ShouldProcess and ShouldContinue methods that are used to get
          user feedback before an action is performed.

        - The ThrowTerminatingError method for generating error records.

        - Several Write methods that return different types of output.

        - Several Write methods that return different types of output.

    All the methods and properties of the PSCmdlet class are available to
    advanced functions. For more information about these methods and
    properties, see System.Management.Automation.PSCmdlet in the MSDN
    (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkId=142139.

  Input Processing Methods

      The methods described in this section are referred to as the input
      processing methods. For functions, these three methods are represented
      by the Begin, Process, and End blocks of the function. Each function
      must include one or more of these blocks. The Windows PowerShell runtime
      uses the code within these blocks when it is running a function. (These
      blocks are also available to functions that do not use the CmdletBinding
      attribute.)

    Begin
      This block is used to provide optional one-time preprocessing for the
      function. The Windows PowerShell runtime uses the code in this block one
      time for each instance of the function in the pipeline.

    Process
      This block is used to provide record-by-record processing for the
      function. This block might be used any number of times, or not at all,
      depending on the input to the function. For example, if the function is
      the first command in the pipeline, the Process block will be used one
      time. If the function is not the first command in the pipeline, the
      Process block is used one time for every input that the function
      receives from the pipeline. If there is no pipeline input, the Process
      block is not used.

      This block must be defined if a function parameter is set to accept
      pipeline input. If this block is not defined and the parameter accepts
      input from the pipeline, the function will miss the values that are
      passed to the function through the pipeline.

      Also, when the function supports confirmation requests (when the
      SupportsShouldProcess parameter of the Parameter attribute is set to
      $True), the call to the ShouldProcess method must be made from within
      the Process block.

    End
      This block is used to provide optional one-time post-processing for
      the function.

      The following example shows the outline of a function that contains a
      Begin block for one-time preprocessing, a Process block for multiple
      record processing, and an End block for one-time post-processing.

          Function Test-ScriptCmdlet
          {
            [CmdletBinding(SupportsShouldProcess=$True)]
            Param ($Parameter1)
            Begin{}
            Process{}
            End{}
          }

  Confirmation Methods

    ShouldProcess
      This method is called to request confirmation from the user before the
      function performs an action that would change the system. The function
      can continue based on the Boolean value returned by the method. This
      method can be called only from within the Process{} block of the
      function. And, the CmdletBinding attribute must declare that the
      function supports ShouldProcess (as shown in the previous example).

      For more information about this method, see
      System.Management.Automation.Cmdlet.ShouldProcess in the MSDN library at
      http://go.microsoft.com/fwlink/?LinkId=142142.

      For more information about how to request confirmation, see
      "Requesting Confirmation" in the MSDN library at
      http://go.microsoft.com/fwlink/?LinkID=136658.

    ShouldContinue
      This method is called to request a second confirmation message. It
      should be called when the ShouldProcess method returns $true. For more
      information about this method, see
      System.Management.Automation.Cmdlet.ShouldContinue in the MSDN library
      at http://go.microsoft.com/fwlink/?LinkId=142143.

  Error Methods

    Functions can call two different methods when errors occur. When a
    nonterminating error occurs, the function should call the WriteError
    method, which is described in the "Write Methods" section. When a
    terminating error occurs and the function cannot continue, it should call
    the ThrowTerminatingError method. You can also use the Throw statement for
    terminating errors and the Write-Error cmdlet for nonterminating errors.

    For more information, see System.Management.Automation.Cmdlet.
    ThrowTerminatingError in the MSDN libray at
    http://go.microsoft.com/fwlink/?LinkId=142144.

  Write Methods

      A function can call the following methods to return different types of
      output. Notice that not all the output goes to the next command in the
      pipeline. You can also use the various Write cmdlets, such as
      Write-Error.

    WriteCommandDetail
      For information about the WriteCommandDetails method, see
      System.Management.Automation.Cmdlet.WriteCommandDetail in the MSDN
      library at http://go.microsoft.com/fwlink/?LinkId=142155.

    WriteDebug
      To provide information that can be used to troubleshoot a function,
      make the function call the WriteDebug method. This displays debug
      messages to the user. For more information, see
      System.Management.Automation.Cmdlet.WriteDebug in the MSDN library
      at http://go.microsoft.com/fwlink/?LinkId=142156.

    WriteError
      Functions should call this method when nonterminating errors occur and
      the function is designed to continue processing records. For more
      information, see System.Management.Automation.Cmdlet.WriteError in the
      MSDN library at http://go.microsoft.com/fwlink/?LinkId=142157.

      Note: If a terminating error occurs, the function should call the
            ThrowTerminatingError method.

    WriteObject
      This method allows the function to send an object to the next command in
      the pipeline. In most cases, this is the method to use when the function
      returns data. For more information, see
      System.Management.Automation.PSCmdlet.WriteObject in the MSDN library at
      http://go.microsoft.com/fwlink/?LinkId=142158.

    WriteProgress
      For functions whose actions take a long time to complete, this method
      allows the function to call the WriteProgress method so that progress
      information is displayed. For example, you can display the percent
      completed. For more information, see
      System.Management.Automation.PSCmdlet.WriteProgress in the MSDN library
      at http://go.microsoft.com/fwlink/?LinkId=142160.

    WriteVerbose
      To provide detailed information about what the function is doing, make
      the function call the WriteVerbose method to display verbose messages to
      the user. By default, verbose messages are not displayed. For more
      information, see System.Management.Automation.PSCmdlet.WriteVerbose
      in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142162.

    WriteWarning
      To provide information about conditions that may cause unexpected
      results, make the function call the WriteWarning method to display
      warning messages to the user. By default, warning messages are displayed.
      For more information, see
      System.Management.Automation.PSCmdlet.WriteWarning in the MSDN library
      at http://go.microsoft.com/fwlink/?LinkId=142164.

      Note: You can also display warning messages by configuring the
            WarningPreference variable or by using the Verbose and Debug
            command-line options.

  Other Methods and Properties

      For information about the other methods and properties that can be
      accessed through the $PSCmdlet variable, see
      System.Management.Automation.PSCmdlet in the MSDN library at
      http://go.microsoft.com/fwlink/?LinkId=142139.

      For example, the ParameterSetName property allows you to see the parameter
      set that is being used. Parameter sets allow you to create a function that
      performs different tasks based on the parameters that are specified when
      the function is run.

SEE ALSO
    about_Functions_Advanced
    about_Functions_CmdletBindingAttributes
    about_Functions_Advanced_Parameters


about_Functions_Advanced_Parameters

TOPIC
    about_Functions_Advanced_Parameters

SHORT DESCRIPTION
    Explains how to add static and dynamic parameters to functions that declare
    the CmdletBinding attribute.

LONG DESCRIPTION
    You can declare your own parameters when you write functions, and you can
    write functions so that they can access the common parameters that are
    available to compiled cmdlets. For more information about the
    Windows PowerShell common parameters, see about_CommonParameters.

 Static Parameters

    The following example shows a parameter declaration that defines a
    ComputerName parameter. This parameter has the following characteristics:

        - It is required.
        - It takes input from the pipeline.
        - It takes an array of strings as input.

        Param
          (
            [parameter(Mandatory=$true,
            ValueFromPipeline=$true)]
            [String[]]
            $ComputerName
          )

    The only required attribute that must be used when you declare a parameter
    is the Parameter attribute. However, you can also declare the Alias
    attribute and several validation arguments. There are no limits to the
    number of attributes that you can add to a parameter declaration.

  Parameter Attribute

      The Parameter attribute is used to declare a parameter of the function.
      This attribute has the following named arguments that are used to define
      the characteristics of the parameter, such as whether the parameter is
      required or optional.

    Mandatory Named Argument

        The Mandatory argument indicates that the parameter is required when
        the function is run. If this argument is not specified, the parameter
        is an optional parameter. The following example shows the declaration
        of a parameter that is required when the function is run.

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            $ComputerName
          )

    Position Named Argument

        The Position argument specifies the position of the parameter. If this
        argument is not specified, the parameter name or its alias must be
        explicitly specified when the parameter is set. Also, if none of the
        parameters of a function have positions, the Windows PowerShell runtime
        assigns positions to each parameter based on the order in which the
        parameters are received.

        The following example shows the declaration of a parameter whose value
        must be specified as the first argument when the cmdlet is run. Notice
        that this function could be run with or without specifying the name of
        the parameter.

        Param
          (
            [parameter(Position=0)]
            [String[]]
            $ComputerName
          )

    ParameterSetName Named Argument

        The ParameterSetName argument specifies the parameter set to which a
        parameter belongs. If no parameter set is specified, the parameter
        belongs to all the parameter sets defined by the function. This
        behavior means that each parameter set must have one unique parameter
        that is not a member of any other parameter set. The following example
        shows the parameter declaration of two parameters that belong to two
        different parameter sets.

        Param
          (
            [parameter(Mandatory=$true,
                      ParameterSetName=”Computer”)]
            [String[]]
            $ComputerName
          )

        Param
          (
            [parameter(Mandatory=$true,
                      ParameterSetName=”User”)]
            [String[]]
            $UserName
          )

        For more information about parameter sets, see "Cmdlet Parameter Sets"
        in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142183.

    ValueFromPipeline Named Argument

        The ValueFromPipeline argument specifies that the parameter accepts
        input from a pipeline object. Specify this argument if the cmdlet
        accesses the complete object, not just a property of the object. The
        following example shows the parameter declaration of a mandatory
        ComputerName parameter that accepts the input object that is passed
        to the function from the pipeline.

        Param
          (
            [parameter(Mandatory=$true,
                      ValueFromPipeline=$true)]
            [String[]]
            $ComputerName
          )

    ValueFromPipelineByPropertyName Named Argument

        The valueFromPipelineByPropertyName argument specifies that the
        parameter accepts input from a property of a pipeline object. Specify
        this attribute if the following conditions are true:

            - The parameter accesses a property of the piped object.

            - The property has the same name as the parameter, or the property
              has the same alias as the parameter.

        For example, if the function has a ComputerName parameter, and the
        piped object has a ComputerName property, the value of the ComputerName
        property is assigned to the ComputerName parameter of the function.

        The following example shows the parameter declaration of a ComputerName
        parameter that accepts input from the ComputerName property of the
        input object that is passed to the cmdlet.

        Param
          (
            [parameter(Mandatory=$true,
                      ValueFromPipelineByPropertyName=$true)]
            [String[]]
            $ComputerName
          )

    ValueFromRemainingArguments Named Argument

        The ValueFromRemainingArguments argument specifies that the parameter
        accepts all of the remaining arguments that are not bound to the
        parameters of the function. The following example shows the parameter
        declaration of a ComputerName parameter that accepts all the remaining
        arguments of the input object that is passed to the function.

        Param
          (
            [parameter(Mandatory=$true,
                      ValueFromRemainingArguments=$true)]
            [String[]]
            $ComputerName
          )

    HelpMessage Named Argument

        The HelpMessage argument specifies a message that contains a short
        description of the parameter. The following example shows a parameter
        declaration that provides a description of the parameter.

        Param
          (
            [parameter(Mandatory=$true,
                      HelpMessage=”An array of computer names.”)]
            [String[]]
            $ComputerName
          )

  Alias Attribute

      The Alias attribute specifies another name for the parameter. There is
      no limit to the number of aliases that can be assigned to a parameter.
      The following example shows a mandatory parameter declaration that adds
      the "CN" alias to the ComputerName parameter.

        Param
          (
            [parameter(Mandatory=$true)]
            [alias(“CN”)]
            [String[]]
            $ComputerName
          )

  Parameter Validation Attributes

      These attributes define how the Windows PowerShell runtime validates the
      arguments of advanced functions.

    AllowNull Validation Attribute

        The AllowNull attribute allows the argument of a mandatory cmdlet
        parameter to be set to Null. In the following example, the ComputerName
        parameter can  contain a value of Null even though this parameter is a
        mandatory parameter.

        Param
          (
            [parameter(Mandatory=$true)]
            [String]
            [AllowNull]
            $ComputerName
          )

    AllowEmptyString Validation Attribute

        The AllowEmptyString attribute allows an empty string as the argument
        of a mandatory cmdlet parameter. In the following example, the
        ComputerName parameter can contain an empty string ("") even though
        this parameter is a mandatory parameter.

        Param
          (
            [parameter(Mandatory=$true)]
            [String]
            [AllowEmptyString]
            $ComputerName
          )

    AllowEmptyCollection Validation Attribute

        The AllowEmptyCollection attribute allows an empty collection as the
        argument of a mandatory parameter.

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            [AllowEmptyCollection]
            $ComputerName
          )

    ValidateCount Validation Attribute

        The ValidateCount attribute specifies the minimum and maximum number
        of arguments that the parameter can accept. The Windows PowerShell
        runtime generates an error if the number of arguments is outside that
        range. In the following example, the ComputerName parameter can have
        one to five arguments.

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateCount(1,5)]
            $ComputerName
          )

    ValidateLength Validation Attribute

        The ValidateLength attribute specifies the minimum and maximum length
        of the parameter argument. The Windows PowerShell runtime generates an
        error if the length of the parameter argument is outside that range.
        In the following example, the specified computer names must have one
        to 10 characters.

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateLength(1,10)]
            $ComputerName
          )

    ValidatePattern Validation Attribute

        The ValidatePattern attribute specifies a regular expression that
        validates the pattern of the parameter argument. The Windows PowerShell
        runtime generates an error if the parameter argument does not match
        this pattern. In the following example, the argument of the parameter
        must be a four-digit number, and each digit must be a number 0 to 9.

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidatePattern("[0-9][0-9][0-9][0-9]")]
            $ComputerName
          )

    ValidateRange Validation Attribute

        The ValidateRange attribute specifies the minimum and maximum values
        of the parameter argument. The Windows PowerShell runtime generates
        an error if the parameter argument is outside that range. In the
        following example, the argument of the parameter cannot be less than
        0 or greater than 10.

        Param
          (
            [parameter(Mandatory=$true)]
            [Int[]]
            [ValidateRange(0,10)]
            $Count
          )

    ValidateScript Validation Attribute

        The ValidateScript attribute specifies a script that is used to
        validate the parameter argument. The Windows PowerShell runtime
        generates an error if the script result is false or if the script
        throws an exception. In the following example the value of the Count
        parameter must be less than 4.

        Param
          (
            [parameter()]
            [Int]
            [ValidateScript({$_ -lt 4})]
            $Count
          )

    ValidateSet Attribute

        The ValidateSet attribute secifies a set of valid values for the
        argument of the parameter. The Windows PowerShell runtime generates
        an error if the parameter argument does not match a value in the set.
        In the following example, the argument of the parameter can contain
        only the names Steve, Mary, and Carl.

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateRange(“Steve”, “Mary”, “Carl”)]
            $UserName
          )

    ValidateNotNull Validation Attribute

        The ValidateNotNull attribute specifies that the argument of the
        parameter cannot be set to Null. The Windows PowerShell runtime
        generates an error if the parameter value is Null.

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateNotNull]
            $UserName
          )

    ValidateNotNullOrEmpty Validation Attribute

        The ValidateNotNullOrEmpty attribute specifies that the argument of
        the parameter cannot be set to Null or it cannot be empty. The Windows
        PowerShell runtime generates an error if the parameter is specified
        but its value is Null, an empty string, or an empty array.

        Param
          (
            [parameter(Mandatory=$true)]
            [String[]]
            [ValidateNotNullOrEmpty]
            $UserName
          )

 Dynamic Parameters

    Dynamic parameters are parameters of a cmdlet, function, or script
    that are available only under certain conditions.

    For example, several provider cmdlets have parameters that are
    available only when the cmdlet is used in the provider path.
    One familiar dynamic parameter is the Encoding parameter of the
    Set-Item, cmdlet, which is available only when the Set-Item cmdlet
    is used in a FileSystem provider path.

    To create a dynamic parameter for a function or script, use the
    DynamicParam keyword.

    The syntax is as follows.

      DynamicParam {<statement-list>}

    In the statement list, use an If statement to specify the
    conditions under which the parameter is available in the function.

    Use the New-Object cmdlet to create a
    System.Management.Automation.RuntimeDefinedParameter object to
    represent the parameter and specify its name.

    You can also use a New-Object command to create a
    System.Management.Automation.ParameterAttribute object to represent
    attributes of the parameter, such as Mandatory, Position, or
    ValueFromPipeline or its parameter set.

    The following example shows a sample function with standard
    parameters called Name and Path, and an optional dynamic parameter
    named DP1. The DP1 parameter is in the PSet1 parameter set and has
    a type of Int32. The DP1 parameter is available in the Sample
    function only when the value of the Path parameter contains "HKLM:",
    indicating that it is being used in the HKEY_LOCAL_MACHINE registry
    drive.

    function Sample {
      Param ([String]$Name, [String]$Path)

      DynamicParam
      {
        if ($path -match "*HKLM*:")
        {
          $dynParam1 = new-object
            System.Management.Automation.RuntimeDefinedParameter("dp1",
            [Int32], $attributeCollection)

          $attributes = new-object System.Management.Automation.ParameterAttribute
          $attributes.ParameterSetName = 'pset1'
          $attributes.Mandatory = $false

          $attributeCollection = new-object
            -Type System.Collections.ObjectModel.Collection``1[System.Attribute]
          $attributeCollection.Add($attributes)

          $paramDictionary = new-object
            System.Management.Automation.RuntimeDefinedParameterDictionary
          $paramDictionary.Add("dp1", $dynParam1)

          return $paramDictionary
        } End if
      }
    }

    For more information, see "RuntimeDefinedParameter Class" in
    the MSDN (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkID=145130.

SEE ALSO
    about_Advanced Functions
    about_Functions_Advanced_Methods
    about_Functions_CmdletBindingAttribute


about_Functions_CmdletBindingAttribute

TOPIC
    about_Functions_CmdletBindingAttribute

SHORT DESCRIPTION
    Describes an attribute that declares a function that acts similar to a
    compiled cmdlet.

LONG DESCRIPTION
    When you write functions, you can add the CmdletBinding attribute so that
    Windows PowerShell will bind the parameters of the function in the same
    way that it binds the parameters of compiled cmdlets. When this attribute
    is declared, Windows PowerShell also sets the $PSCmdlet automatic variable.

    When you use cmdlet binding, unknown parameters and positional arguments
    that have no matching positional parameters cause parameter binding to
    fail. Also, a function or script with cmdlet binding does not use the
    $args variable.

    Note: Compiled cmdlets use the required Cmdlet attribute, which is similar
          to the CmdletBinding attribute that is described in this topic.

    The following example shows the outline of a function that specifies all
    the optional arguments of the CmdletBinding attribute. A brief description
    of each argument follows this example.

        {
          [CmdletBinding(SupportsShouldProcess=<Boolean>,
                     ConfirmImpact=<String>,
                     DefaultParameterSetName=<String>)]

          Param ($Parameter1)
          Begin{}
          Process{}
          End{}
        }

  SupportsShouldProcess

      When the SupportsShouldProcess argument is set to true, it indicates that
      the function supports calls to the ShouldProcess method, which is used to
      prompt the user for feedback before the function makes a change to the
      system. When this argument is specified, the Confirm and WhatIf
      parameters are enabled for the function.

      For more information about confirmation requests, see "Requesting
      Confirmation" in the MSDN (Microsoft Developer Network) library at
      http://go.microsoft.com/fwlink/?LinkId=136658.

  DefaultParameterSetName

      The DefaultParameterSetName argument specifies the name of the parameter
      set that Windows PowerShell will attempt to use when it cannot determine
      which parameter set to use. You can avoid this issue by making the
      unique parameter of each parameter set a mandatory parameter.

  ConfirmImpact

      The ConfirmImpact argument specifies when the action of the function
      should be confirmed by a call to the ShouldProcess method. The call to
      the ShouldProcess method displays a confirmation prompt only when the
      ConfirmImpact argument is equal to or greater than the value of the
      $ConfirmPreference preference variable. (The default value of the
      argument is Medium.) Specify this argument only when the
      SupportsShouldProcess argument is also specified.

SEE ALSO
    about_Functions_Advanced
    about_Functions_CmdletBindingAttribute
    about_Functions_ParameterAttributes


about_Hash_Tables

TOPIC
    about_Hash_Tables

SHORT DESCRIPTION
    Describes how to create, use, and sort hash tables in Windows PowerShell.

LONG DESCRIPTION
    A hash table, also known as a dictionary or associative array, is a
    compact data structure that stores one or more name/value pairs. For
    example, a hash table might contain a series of names and employee IDs,
    computer names and IP addresses, or message IDs and message text.

    Hash tables are frequently used because they are very efficient for finding
    and retrieving data. You can use hash tables to store lists and to create
    calculated properties in Windows PowerShell. And, Windows PowerShell has a
    cmdlet, ConvertFrom-StringData, that converts strings to a hash table.

  Creating Hash Tables
      The items in a hash table are arranged in name/value pairs, such as:

          Msg1="Please enter your password."
          Msg2="The path parameter is required."
          Msg3="The alias of Get-Command is gcm."

      The values are mapped to or associated with the names so that when you
      submit the name, Windows PowerShell returns the value.

      In Windows PowerShell, the syntax of a hash table is as follows:

          @{ <name> = <value>; [<name> = <value> ] ...}

      When you create a hash table, follow these guidelines:

          - Begin the hash table with an at sign (@).

          - Enclose the hash table in braces ({}).

          - Enter one or more name-value pairs for the content of the hash
            table.

          - Use an equal sign (=) to separate each name from its value.

          - Use a semicolon (;) to separate the name/value pairs.

          - If a name or value contains spaces, enclose it in quotation marks.

      For example, a hash table of the previous user messages looks like this:

          @{
          Msg1="Please enter your password.";
          Msg2="The path parameter is required.";
          Msg3="The alias of Get-Command is gcm.";
          }

      To use a hash table in scripts and commands, save it in a variable. The
      value of the variable is a hash table object
      (System.Collections.Hashtable), and each name in the name/value pairs
      is a property of the hash table object.

      The following commands save the user-message hash table in the $a
      variable and use the dot method to display the values.

          C:\PS> $a = @{
          >> Msg1="Please enter your password.";
          >> Msg2="The path parameter is required.";
          >> Msg3="The alias of Get-Command is gcm.";
          >> }

          C:\PS> $a
          Name                           Value
          ----                           -----
          Msg1                    Please enter your password.
          Msg3                    The alias of Get-Command is gcm.
          Msg2                    The path parameter is required.

          C:\PS> $a.Msg1
          Please enter your password.

      Hash tables are not limited to one type of data. You can enter any data
      type in a hash table, and you can combine data types in a single hash
      table. For example, you can build a hash table that contains an integer,
      a call to a cmdlet, and a string.

  Sorting Hash Tables
      To sort the hash table alphabetically by keys or values, use the
      GetEnumerator method of hash tables to get the keys and values in the
      hash table, and then use the Sort-Object cmdlet to sort them.

      For example, the following command sorts the hash table in $a
      alphabetically by keys.

          C:\PS> $a.getenumerator() | sort-object -property key

          Name                           Value
          ----                           -----
          Msg1                           Please enter your password.
          Msg2                           The path parameter is required.
          Msg3                           The alias of Get-Command is gcm.

      The following command uses the same method to sort the hash values in
      descending order.

          C:\PS> $a.getenumerator() | sort-object -property value -descending

          Name                           Value
          ----                           -----
          Msg2                           The path parameter is required.
          Msg3                           The alias of Get-Command is gcm.
          Msg1                           Please enter your password.

  ConvertFrom-StringData
      The ConvertFrom-StringData cmdlet converts a string or a here-string of
      name/value pairs into a hash table. You can use the
      ConvertFrom-StringData cmdlet safely in the Data section of a script,
      and you can use it with the Import-LocalizedData cmdlet to display user
      messages in the user-interface (UI) culture of the current user.

      Here-strings are especially useful when the values in the hash table
      include quotation marks. (For more information about here-strings, see
      about_Quoting_Rules.)

      The following example shows how to create a here-string of the user
      messages in the previous example and how to use ConvertFrom-StringData
      to convert them from a string into a hash table.

      The following command creates a here-string of the name/value pairs and
      then saves it in the $string variable.

          C:\PS> $string = @"
          Msg1="Please enter your password."
          Msg2="The path parameter is required."
          Msg3="The alias of Get-Command is gcm."
          "@

    This command uses the ConvertFrom-StringData cmdlet to convert the
    here-string into a hash table.

        C:\PS> convertfrom-stringdata $string

        Name                           Value
        ----                           -----
        Msg3                           "The alias of Get-Command is gcm."
        Msg2                           "The path parameter is required."
        Msg1                           "Please enter your password."

SEE ALSO
    about_Arrays
    about_Quoting_Rules
    about_Script_Internationalization
    ConvertFrom-StringData
    Import-LocalizedData


about_History

TOPIC
    about_History

SHORT DESCRIPTION
    Describes how to retrieve and run commands in the command history.

LONG DESCRIPTION
    When you enter a command at the command prompt, Windows PowerShell
    saves the command in the command history. You can use the commands
    in the history as a record of your work. And, you can recall and run the
    commands from the command history.

  History Cmdlets
      Windows PowerShell has a set of cmdlets that manage the command history.

          Cmdlet (Alias)       Description
          -------------------  ------------------------------------------
          Get-History (h)      Gets the command history.

          Invoke-History (r)   Runs a command in the command history.

          Add-History          Adds a command to the command history.

          Clear-History (clh)  Deletes commands from the command history.

  Keyboard Shortcuts for Managing History
      In the Windows PowerShell console, you can use the following shortcuts
      to manage the command history.

      For other host applications, see the product documentation.

          Use this key      To perform this action
          -------------     ----------------------------------------------
          UP ARROW          Displays the previous command.

          DOWN ARROW        Displays the next command.

          F7                Displays the command history.
                            To hide the history, press ESC.

          F8                Finds a command. Type one or more characters,
                            and then press F8. For the next instance,
                            press F8 again.

          F9                Find a command by history ID. Type the history
                            ID, and then press F9. To find the ID, press F7.

  MaximumHistoryCount
      The $MaximumHistoryCount preference variable determines the maximum
      number of commands that Windows PowerShell saves in the command history.
      The default value is 64, meaning that Windows PowerShell saves the 64
      most recent commands, but you can change the value of the variable.

      For example, the following command raises the $MaximumHistoryCount to
      100 commands:

          $MaximumHistoryCount = 100

      To apply the setting, restart Windows PowerShell.

      To save the new variable value for all your Windows PowerShell
      sessions, add the assignment statement to a Windows PowerShell profile.
      For more information, see about_Profiles.

  Order of Commands in the History
      Commands are added to the history when the command finishes executing,
      not when the command is entered. If commands take some time to be
      completed, or if the commands are executing in a nested prompt, the
      commands might appear to be out of order in the history. (Commands
      that are executing in a nested prompt are completed only when you exit
      the prompt level.)

SEE ALSO
    about_Line_Editing
    about_Variables
    about_Preference_Variables


about_If

TOPIC
    about_If

SHORT DESCRIPTION
    Describes a language command you can use to run statement lists based
    on the results of one or more conditional tests.

LONG DESCRIPTION
    You can use the If statement to run code blocks if a specified
    conditional test evaluates to true. You can also specify one or more
    additional conditional tests to run if all the prior tests evaluate to
    false. Finally, you can specify an additional code block that is run if
    no other prior conditional test evaluates to true.

  Syntax
    The following example shows the If statement syntax:

        if (<test1>)
            {<statement list 1>}
        [elseif (<test2>)
            {<statement list 2>}]
        [else
            {<statement list 3>}]

    When you run an If statement, Windows PowerShell evaluates the
    <test1> conditional expression as true or false. If <test1> is true,
    <statement list 1> runs, and Windows PowerShell exits the If statement.
    If <test1> is false, Windows PowerShell evaluates the condition specified
    by the <test2> conditional statement.

    If <test2> is true, <statement list 2> runs, and Windows PowerShell
    exits the If statement. If both <test1> and <test2> evaluate to false,
    the <statement list 3> code block runs, and Windows PowerShell exits
    the If statement.

    You can use multiple Elseif statements to chain a series of conditional
    tests so that each test is run only if all the previous tests are
    false. If you need to create an If statement that contains many
    Elseif statements, consider using a Switch statement instead.

  Examples
    The simplest If statement contains a single command
    and does not contain any Elseif statements or any Else statements. The
    following example shows the simplest form of the If statement:

        if ($a -gt 2)
        {
            Write-Host "The value $a is greater than 2."
        }

    In this example, if the $a variable is greater than 2, the condition
    evaluates to true, and the statement list runs. However, if $a is less
    than or equal to 2 or is not an existing variable, the If statement does
    not display a message. By adding an Else statement, a message is displayed
    when $a is less than or equal to 2, as the next example shows:

        if ($a -gt 2)
        {
            Write-Host "The value $a is greater than 2."
        }
        else
        {
            Write-Host "The value $a is less than or equal to 2, is not
        created or is not initialized."
        }

    To further refine this example, you can use the Elseif statement to
    display a message when the value of $a is equal to 2, as the next
    example shows:

        if ($a -gt 2)
        {
            Write-Host "The value $a is greater than 2."
        }
        elseif ($a -eq 2)
        {
            Write-Host "The value $a is equal to 2."
        }
        else
        {
            Write-Host "The value $a is less than 2 or was not created
        or initialized."
        }

SEE ALSO
    about_Comparison_Operators
    about_Switch


about_Jobs

TOPIC
    about_Jobs

SHORT DESCRIPTION
    Provides information about how Windows PowerShell background jobs run a
    command or expression in the background without interacting with the
    current session.

LONG DESCRIPTION
    This topic explains how to run background jobs in Windows PowerShell on a
    local computer. For information about running background jobs on remote
    computers, see about_Remote_Jobs.

    When you start a background job, the command prompt returns immediately,
    even if the job takes an extended time to complete. You can continue to
    work in the session without interruption while the job runs.

    Important: Background jobs that are started by using Start-Job or the
               AsJob parameter of Invoke-Command rely on the Windows PowerShell
               remoting infrastructure. To use these features, Windows
               PowerShell must be configured for remoting, even if the
               background job is run only on the local computer.
               For more information, see about_Remote_Requirements.

 HOW TO START A JOB ON THE LOCAL COMPUTER
    To start a background job on the local computer, use the Start-Job
    cmdlet.

    To write a Start-Job command, enclose the command that the job runs in
    braces ( { } ). Use the ScriptBlock parameter to specify the command.

    The following command starts a background job that runs a Get-Process
    command on the local computer.

        start-job -scriptblock {get-process}

    The Start-Job command returns an object that represents the job. The job
    object contains useful information about the job, but it does not contain
    the job results.

    Save the job object in a variable, and then use it with the other Job
    cmdlets to manage the background job. The following command starts a job
    object and saves the resulting job object in the $job variable.

        $job = start-job -scriptblock {get-process}

    You can also use the Get-Job cmdlet to get objects that represent the jobs
    started in the current session. Get-Job returns the same job object that
    Start-Job returns.

 GETTING JOB OBJECTS

    To get object that represent the background jobs that were started in the
    current session, use the Get-Job cmdlet. Without parameters, Get-Job
    returns all of the jobs that were started in the current session.

    For example, the following command gets the jobs in the current session.

    get-job

        Id  Name  State      HasMoreData  Location   Command
        --  ----  -----      -----------  --------   -------
        1   Job1  Running    True         localhost  get-process

    You can also save the job object in a variable and use it to represent the
    job in a later command. The following command gets the job with ID 1 and
    saves it in the $job variable.

       $job = get-job -id 1

    The job object contains the state of the job, which indicates whether the
    job has finished. A finished job has a state of "Complete" or "Failed". A
    job might also be blocked or running.

    get-job

        Id  Name  State      HasMoreData  Location   Command
        --  ----  -----      -----------  --------   -------
        1   Job1  Complete    True         localhost  get-process

 GETTING THE RESULTS OF A JOB

    When you run a background job, the results do not appear immediately.
    Instead, the Start-Job cmdlet returns a job object that represents the
    job, but it does not contain the results. To get the results of a
    background job, use the Receive-Job cmdlet.

    The following command uses the Receive-Job cmdlet to get the results of
    the job. It uses a job object saved in the $job variable to identify the
    job.

    receive-job -job $job

     The Receive-Job cmdlet returns the results of the job.

           Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)    Id ProcessName
           -------  ------    -----      ----- -----   ------    -- -----------
               103       4    11328       9692    56           1176 audiodg
               804      14    12228      14108   100   101.74  1740 CcmExec
               668       7     2672       6168   104    32.26   488 csrss
       ...

     You can also save the results of a job in a variable. The following
     command saves the results of the job in the $job variable to the $results
     variable.

    $results = receive-job -job $job

     And, you can save the results of the job in a file by using the redirection
     operator (>) or the Out-File cmdlet. The following command uses the
     redirection operator to save the results of the job in the $job variable in
     the Results.txt file.

        receive-job -job $job > results.txt

 GETTING AND KEEPING PARTIAL JOB RESULTS

    The Receive-Job cmdlet returns the results of a background job. If the
    job is complete, Receive-Job returns the complete results of the job. If
    the job is still running, Receive-Job gets the results that have been
    generated thus far. You can run Receive-Job commands again to get the
    remaining results.

    When Receive-Job returns results, by default, it deletes the results from
    the cache where job results are stored. If you run another Receive-Job
    command, you get only the results that were not yet received.

    The following commands show the results of Receive-Job commands run
    before the job is complete.

    C:\PS> receive-job -job $job

        Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
        -------  ------    -----      ----- -----   ------     -- -----------
            103       4    11328       9692    56            1176 audiodg
            804      14    12228      14108   100   101.74   1740 CcmExec

    C:\PS> receive-job -job $job

        Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
        -------  ------    -----      ----- -----   ------     -- -----------
             68       3     2632        664    29     0.36   1388 ccmsetup
            749      22    21468      19940   203   122.13   3644 communicator
            905       7     2980       2628    34   197.97    424 csrss
           1121      25    28408      32940   174   430.14   3048 explorer

    To prevent Receive-Job from deleting the job results that it has
    returned, use the Keep parameter. As a result, Receive-Job returns all
    of the results that have been generated until that time.

    The following commands show the effect of using the Keep parameter on a job
    that is not yet complete.

    C:\PS> receive-job -job $job -keep

        Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
        -------  ------    -----      ----- -----   ------     -- -----------
            103       4    11328       9692    56            1176 audiodg
            804      14    12228      14108   100   101.74   1740 CcmExec

    C:\PS> receive-job -job $job -keep

        Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
        -------  ------    -----      ----- -----   ------     -- -----------
            103       4    11328       9692    56            1176 audiodg
            804      14    12228      14108   100   101.74   1740 CcmExec
             68       3     2632        664    29     0.36   1388 ccmsetup
            749      22    21468      19940   203   122.13   3644 communicator
            905       7     2980       2628    34   197.97    424 csrss
           1121      25    28408      32940   174   430.14   3048 explorer

WAITING FOR THE RESULTS

    If you run a command that takes a long time to be completed, you can use
    the properties of the job object to determine when the job is complete.
    The following command uses the Get-Job object to get all of the background
    jobs in the current session.

    get-job

    The results appear in a table. The status of the job appears in the State
    column.

        Id  Name  State      HasMoreData  Location   Command
        --  ----  -----      -----------  --------   -------
        1   Job1  Complete    True         localhost  get-process
        2   Job2  Running     True         localhost  get-eventlog -log syst...
        3   Job3  Complete    True         localhost  dir -path c:\* -recurse

    In this case, the State property reveals that Job 2 is still running. If
    you were to use the Receive-Job cmdlet to get the job results now, the
    results would be incomplete. You can use the Receive-Job cmdlet
    repeatedly to get all of the results. By default, each time you use it,
    you get only the results that were not already received, but you can use
    the Keep parameter of the Receive-Job cmdlet to retain the results, even
    though they were already received.

    At this point, you can write the results to a file and then append the
    newly received results as they arrive. Or, you can wait and check the
    state of the job later.

    Or, you can use the Wait-Job cmdlet to wait for any or all of the results
    of the job. Wait-Job lets you wait for a particular job, for all jobs, or
    for any of the jobs to be completed.

    The following command uses the Wait-Job cmdlet to wait for a job with
    ID 10.

    wait-job -ID 10

    As a result, the Windows PowerShell prompt is suppressed until the job
    is completed.

    You can also wait for a predetermined period of time. This command uses
    the Timeout parameter to limit the wait to 120 seconds. When the time
    expires, the command prompt returns, but the job continues to run in the
    background.

    wait-job -ID 10 -timeout 120

STOPPING A JOB

    To stop a background job, use the Stop-Job cmdlet. The following command
    starts a job to get every entry in the System event log. It saves the job
    object in the $job variable.

    $job = start-job -scriptblock {get-eventlog -log system}

    The following command stops the job. It uses a pipeline operator (|) to
    send the job in the $job variable to Stop-Job.

    $job | stop-job

DELETING A JOB

    To delete a background job, use the Remove-Job cmdlet. The following
    command deletes the job in the $job variable.

    remove-job -job $job

INVESTIGATING A FAILED JOB

    To find out why a job failed, use the Reason subproperty of the job object.

    The following command starts a job without the required credentials. It
    saves the job object in the $job variable.

         $job = start-job -scriptblock {new-item -path HKLM:\Software\MyCompany}

         Id   Name  State    HasMoreData  Location   Command
         --   ----  -----    -----------  --------   -------
         1    Job1  Failed   False         localhost  new-item -path HKLM:\S...

    The following command uses the Reason property to find the error that
    caused the job to fail.

         $job.ChildJobs[0].JobStateInfo.Reason

    In this case, the job failed because the remote computer required explicit
    credentials to run the command. The value of the Reason property is:

         Connecting to remote server failed with the following error
         message : Access is denied.

THE JOB CMDLETS

    Start-Job        Starts a background job on a local computer.

    Get-Job          Gets the background jobs that were started in the current
                     session.

    Receive-Job      Gets the results of background jobs.

    Stop-Job         Stops a background job.

    Wait-Job         Suppresses the command prompt until one or all jobs are
                     complete.

    Remove-Job       Deletes a background job.

    Invoke-Command   The AsJob parameter runs any command as a background job on a
                     remote computer. You can also use Invoke-Command to run
                     any job command remotely, including a Start-Job command.

SEE ALSO
   about_Remote_Jobs
   about_Job_Details
   about_Remote
   about_PSSessions
   Start-Job
   Get-Job
   Receive-Job
   Stop-Job
   Wait-Job
   Remove-Job
   Invoke-Command


about_Job_Details

TOPIC
  about_Job_Details

SHORT DESCRIPTION
  Provides details about background jobs on local and remote computers.

DETAILED DESCRIPTION
   This topic explains the concept of a background job and provides technical
   information about how background jobs work in Windows PowerShell.

   This topic is a supplement to the about_Jobs and about_Remote_Jobs topics.

   Important: Background jobs that are started by using Start-Job or the AsJob
              parameter of Invoke-Command rely on the Windows PowerShell
              remoting infrastructure. To use these features, Windows
              PowerShell must be configured for remoting, even if the
              background job is runs only on the local computer.
              For more information, see about_Remote_Requirements.

 ABOUT BACKGROUND JOBS
    A background job runs a command or expression asynchronously. It might run
    a cmdlet, a function, a script, or any other command-based task. It is
    designed to run commands that take an extended period of time, but you
    can use it to run any command in the background.

    When a synchronous command runs, the Windows PowerShell command prompt is
    suppressed until the command is complete. But a background job does not
    suppress the Windows PowerShell prompt. A command to start a background job
    returns a job object. The prompt returns immediately so you can work on
    other tasks while the background job runs.

    However, when you start a background job, you do not get the results
    immediately even if the job runs very quickly. The job object that is
    returned contains useful information about the job, but it does not contain
    the job results. You must run a separate command to get the job results.
    You can also run commands to stop the job, to wait for the job to be
    completed, and to delete the job.

    To make the timing of a background job independent of other commands, each
    background job runs in its own Windows PowerShell environment
    (a "session"). However, this can be a temporary connection that is created
    only to run the job and is then destroyed, or it can be a persistent
    session (a PSSession) that you can use to run several related jobs or
    commands.

 USING THE JOB CMDLETS
    Use a Start-Job command to start a background job on a local computer.
    Start-Job returns a job object. You can also get objects representing the
    jobs that were started on the local computer by using the Get-Job cmdlet.

    To get the job results, use a Receive-Job command. If the job is not
    complete, Receive-Job returns partial results. You can also use the
    Wait-Job cmdlet to suppress the command prompt until one or all of the
    jobs that were started in the session are complete.

    To stop a background job, use the Stop-Job cmdlet. To delete a job, use
    the Remove-Job cmdlet.

    For more information about how the cmdlets work, see the Help topic for
    each cmdlet, and see about_Jobs.

 STARTING BACKGROUND JOBS ON REMOTE COMPUTERS
    You can create and manage background jobs on a local or remote computer. To
    run a background job remotely, use the AsJob parameter of a cmdlet such as
    Invoke-Command, or use the Invoke-Command cmdlet to run a Start-Job
    command remotely. You can also start a background job in an interactive
    session.

    For more information about remote background jobs, see about_Remote_Jobs.

 CHILD JOBS
    Each background job consists of a parent job and one or more child jobs. In
    jobs started by using Start-Job or the AsJob parameter of Invoke-Command,
    the parent job is an executive. It does not run any commands or return any
    results. The commands are actually run by the child jobs. (Jobs started by
    using other cmdlets might work differently.)

    The child jobs are stored in the ChildJobs property of the parent job
    object. The ChildJobs property can contain one or many child job objects.
    The child job objects have a name, ID, and instance ID that differ
    from the parent job so that you can manage the parent and child jobs
    individually or as a unit.

    To see the parent and child jobs in a job, use the Get-Job cmdlet to get
    the parent job, and then pipe the job to a Format-List command that displays
    the Name and ChildJobs properties of the objects, as shown in the following
    command.

        C:\PS> get-job | format-list -property Name, ChildJobs

        Name          : Job1
        ChildJobs     : {Job2}

    You can also use a Get-Job command on the child job, as shown in the
    following command:

        C:\PS> get-job job2

        Id    Name   State      HasMoreData   Location    Command
        --    ----   -----      -----------   --------    -------
        2     Job2   Completed  True          localhost   get-process

    The configuration of the child job depends on the command that you use to
    start the job.

       -- When you use Start-Job to start a job on a local computer, the job
          consists of an executive parent job and a child job that runs the
          command.

       -- When you use the AsJob parameter of Invoke-Command to start a job on
          one or more computers, the job consists of an executive parent job
          and a child job for each job run on each computer.

       -- When you use Invoke-Command to run a Start-Job command on one or more
          remote computers, the result is the same as a local command run on
          each remote computer. The command returns a job object for each
          computer. The job object consists of an executive parent job and
          one child job that runs the command.

    The parent job represents all of the child jobs. When you manage a parent
    job, you also manage the associated child jobs. For example, if you stop a
    parent job, all child jobs are stopped. If you get the results of a parent
    job, you get the results of all child jobs.

    However, you can also manage child jobs individually. This is most useful
    when you want to investigate a problem with a job or get the results of
    only one of a number of child jobs started by using the AsJob parameter of
    Invoke-Command. (The backtick character [`] is the continuation character.)

    The following command uses the AsJob parameter of Invoke-Command to start
    background jobs on the local computer and two remote computers. The command
    saves the job in the $j variable.

        C:\PS> $j = invoke-command -computername localhost, Server01, Server02 `
               -command {get-date} -AsJob

    When you display the Name and ChildJob properties of the job in $j, it
    shows that the command returned a job object with three child jobs, one for
    each computer.

        C:\PS> $j | format-list name, childjobs

        Name      : Job3
        ChildJobs : {Job4, Job5, Job6}

    When you display the parent job, it shows that the job failed.

        C:\PS> $j

        Id   Name    State   HasMoreData     Location             Command
        --   ----    -----   -----------     --------             -------
        1    Job3    Failed  True            localhost,server... get-date

    But when you run a Get-Job command on each of the child jobs, it shows
    that only one failed.

        PS C:\ps-test> get-job job4, job5, job6

        Id   Name   State      HasMoreData     Location           Command
        --   ----   -----      -----------     --------           -------
        4    Job4   Completed  True            localhost          get-date
        5    Job5   Failed     False           Server01           get-date
        6    Job6   Completed  True            Server02           get-date

    To get the results of all child jobs, use the Receive-Job cmdlet to get
    the results of the parent job. But you can also get the results of a
    particular child job, as shown in the following command.

        C:\PS> receive-job -job6 -keep | format-table ComputerName, DateTime -auto

        ComputerName DateTime
        ------------ --------
        Server02     Thursday, March 13, 2008 4:16:03 PM

    The child jobs feature of Windows PowerShell background jobs gives you
    more control over the jobs that you run.

SEE ALSO
    about_Jobs
    about_Remote_Jobs
    about_Remote
    Invoke-Command
    Start-Job
    Get-Job
    Wait-Job
    Stop-Job
    Remove-Job
    New-PSSession
    Enter-PSSession
    Exit-PSSession


about_Join

TOPIC
    about_join

SHORT DESCRIPTION
    Describes how the join operator (-join) combines multiple strings into a
    single string.

LONG DESCRIPTION
    The join operator concatenates a set of strings into a single string. The
    strings are appended to the resulting string in the order that they appear
    in the command.

  Syntax
      The following diagram shows the syntax for the join operator.

    -Join <String[]>
    <String[]> -Join <Delimiter>

  Parameters
      String[]
          Specifies one or more strings to be joined.

      Delimiter
      Specifies one or more characters placed between the concatenated strings.
          The default is no delimiter ("").

  Remarks
      The unary join operator (-join <string[]>) has higher precedence than
      a comma. As a result, if you submit a comma-separated list of strings to
      the unary join operator, only the first string (before the first comma)
      is submitted to the join operator.

      To use the unary join operator, enclose the strings in parentheses, or
      store the strings in a variable, and then submit the variable to join.

      For example:

          -join "a", "b", "c"
          a
          b
          c

          -join ("a", "b", "c")
          abc

          $z = "a", "b", "c"
          -join $z
          abc

  Examples
      The following statement joins three strings:

          -join ("Windows", "PowerShell", "2.0")
          WindowsPowerShell2.0

      The following statement joins three strings delimited by a space:

          "Windows", "PowerShell", "2.0" -join " "
          Windows PowerShell 2.0

      The following statements use a multiple-character delimiter to join
      three strings:

          $a = "WIND", "SP", "ERSHELL"
          $a -join "OW"
          WINDOWSPOWERSHELL

      The following statement joins the lines in a here-string into
      a single string. Because a here-string is one string, the lines in the
      here-string must be split before they can be joined. You can use this
      method to rejoin the strings in an XML file that has been saved in a
      here-string:

          $a = @'
          a
          b
          c
          '@

          (-split $a) -join " "
          a b c

SEE ALSO
    about_Operators
    about_Comparison_Operators
    about_Split


about_Language_Keywords

TOPIC
    about_Language_Keywords

SHORT DESCRIPTION
    Describes the keywords in the Windows PowerShell scripting language.

LONG DESCRIPTION
    Windows PowerShell has the following language keywords. For more
    information, see the about topic for the keyword and the information that
    follows the table.

        Keyword            Reference
        -------            ---------
        Begin              about_Functions, about_Functions_Advanced
        Break              about_Break, about_Trap
        Catch              about_Try_Catch_Finally
        Continue           about_Continue, about_Trap
        Data               about_Data_Sections
        Do                 about_Do, about_While
        Dynamicparam       about_Functions_Advanced_Parameters
        Else               about_If
        Elseif             about_If
        End                about_Functions, about_Functions_Advanced_Methods
        Exit               Described in this topic.
        Filter             about_Functions
        Finally            about_Try_Catch_Finally
        For                about_For
        Foreach            about_Foreach
        From               Reserved for future use.
        Function           about_Functions, about_Functions_Advanced
        If                 about_If
        In                 about_Foreach
        Param              about_Functions
        Process            about_Functions, about_Functions_Advanced
        Return             about_Return
        Switch             about_Switch
        Throw              about_Throw, about_Functions_Advanced_Methods
        Trap               about_Trap, about_Break, about_Try_Catch_Finally
        Try                about_Try_Catch_Finally
        Until              about_Do
        While              about_While, about_Do

  Language Keywords

      Begin
      -----

      Specifies one part of the body of a function, along with the
      Dynamicparam, Process, and End keywords. The Begin statement list runs
      one time before any objects are received from the pipeline.

      Syntax:

          function <name> {
              dynamicparam {<statement list>}
              begin {<statement list>}
              process {<statement list>}
              end {<statement list>}
          }

      Break
      -----

      Causes a script to exit a loop.

      Syntax:

          while (<condition>) {
              <statements>
                   ...
              break
                   ...
              <statements>
          }

      Catch
      -----

      Specifies a statement list to run if an error occurs in the
      accompanying Try statement list. An error type requires brackets. The
      second pair of brackets indicates that the error type is optional.

      Syntax:

          try {<statement list>}
          catch [[<error type>]] {<statement list>}

      Continue
      --------

      Causes a script to stop running a loop and to go back to the condition.
      If the condition is met, the script begins the loop again.

      Syntax:

          while (<condition>) {
              <statements>
                  ...
              continue
                  ...
              <statements>
          }

      Data
      ----

      In a script, defines a section that isolates data from the script logic.
      Can also include If statements and some limited commands.

      Syntax:

      data <variable> [-supportedCommand <cmdlet-name>] {<permitted content>}

      Do
      --

      Used with the While or Until keyword as a looping construct. Windows
      PowerShell runs the statement list at least one time, unlike a loop that
      uses While.

      Syntax:

          do {<statement list>} while (<condition>)

          do {<statement list>} until (<condition>)

      Dynamicparam
      ------------

      Specifies one part of the body of a function, along with the Begin,
      Process, and End keywords. Dynamic parameters are added at run time.

      Syntax:

          function <name> {
              dynamicparam {<statement list>}
              begin {<statement list>}
              process {<statement list>}
              end {<statement list>}
          }

      Else
      ----

      Used with the If keyword to specify the default statement list.

      Syntax:

          if (<condition>) {<statement list>}
          else {<statement list>}

      Elseif
      ------

      Used with the If and Else keywords to specify additional conditionals.
      The Else keyword is optional.

      Syntax:

          if (<condition>) {<statement list>}
          elseif (<condition>) {<statement list>}
          else {<statement list>}

      End
      ---

      Specifies one part of the body of a function, along with the
      Dynamicparam, Begin, and End keywords. The End statement list runs one
      time after all the objects have been received from the pipeline.

      Syntax:

          function <name> {
              dynamicparam {<statement list>}
              begin {<statement list>}
              process {<statement list>}
              end {<statement list>}
          }

      Exit
      ----

      Causes Windows PowerShell to exit a script or a Windows PowerShell
      instance.

      Syntax:

          exit

      Filter
      ------

      Specifies a function in which the statement list runs one time for each
      input object. It has the same effect as a function that contains only a
      Process block.

      Syntax:

          filter <name> {<statement list>}

      Finally
      -------

      Defines a statement list that runs after statements that are associated
      with Try and Catch. A Finally statement list runs even if you press
      CTRL+C to leave a script or if you use the Exit keyword in the script.

      Syntax:

          try {<statement list>}
          catch [<error type] {<statement list>}
          finally {<statement list>}

      For
      ---

      Defines a loop by using a condition.

      Syntax:

          for (<initialize>; <condition>; <iterate>) {<statement list>}

      Foreach
      -------

      Defines a loop by using each member of a collection.

      Syntax:

          foreach (<item> in <collection>){<statement list>}

      From
      -----

      Reserved for future use.

      Function
      --------

      Creates a named statement list of reusable code. You can name the scope a
      function belongs to. And, you can specify one or more named parameters by
      using the Param keyword. Within the function statement list, you can
      include Dynamicparam, Begin, Process, and End statement lists.

      Syntax:

          function [<scope:>]<name> {
              param ([type]<$pname1> [, [type]<$pname2>])
              dynamicparam {<statement list>}
              begin {<statement list>}
              process {<statement list>}
              end {<statement list>}
          }

      You also have the option of defining one or more parameters outside the
      statement list after the function name.

      Syntax:

          function [<scope:>]<name> [([type]<$pname1>, [[type]<$pname2>])] {
              dynamicparam {<statement list>}
              begin {<statement list>}
              process {<statement list>}
              end {<statement list>}
          }

      If
      --

      Defines a conditional.

      Syntax:

          if (<condition>) {<statement list>}

      In
      --

      Used in a Foreach statement to create a loop that uses each member of a
      collection.

      Syntax:

          foreach (<item> in <collection>){<statement list>}

      Param
      -----

      Defines the parameters in a function.

      Syntax:

          function [<scope:>]<name> {
              param ([type]<$pname1>[, [[type]<$pname2>]])
              <statement list>
          }

      Process
      -------

      Specifies a part of the body of a function, along with the Dynamicparam,
      Begin, and End keywords. When a Process statement list receives input
      from the pipeline, the Process statement list runs one time for each
      element from the pipeline. If the pipeline provides no objects, the
      Process statement list does not run. If the command is the first command
      in the pipeline, the Process statement list runs one time.

      Syntax:

          function <name> {
              dynamicparam {<statement list>}
              begin {<statement list>}
              process {<statement list>}
              end {<statement list>}
          }

      Return
      ------

      Causes Windows PowerShell to leave the current scope, such as a script or
      function, and writes the optional expression to the output.

      Syntax:

          return [<expression>]

      Switch
      ------

      Specifies a variety of actions to be performed on items from the pipeline
      or from a file. You can use either of the following syntax models.

      Syntax 1:

          switch [-regex|-wildcard|-exact][-casesensitive] ( pipeline )

          {
              <string>|<number>|<variable>|{ <expression> } {<statement list>}
              <string>|<number>|<variable>|{ <expression> } {<statement list>}
                    ...
              default {<statement list>}
          }

      Syntax 2:

          switch [-regex|-wildcard|-exact][-casesensitive] -file filename
          {
              <string>|<number>|<variable>|{ <expression> } {<statement list>}
              <string>|<number>|<variable>|{ <expression> } {<statement list>}
                    ...
              default {<statement list>}
          }

      Throw
      -----

      Throws an object as an error.

      Syntax:

          throw [<object>]

      Trap
      ----

      Defines a statement list to be run if an error is encountered. An error
      type requires brackets. The second pair of brackets indicates that the
      error type is optional.

      Syntax:

          trap [[<error type>]] {<statement list>}

      Try
      ---

      Defines a statement list to be checked for errors while the statements
      run. If an error occurs, Windows PowerShell continues running in a Catch
      or Finally statement. An error type requires brackets. The second pair of
      brackets indicates that the error type is optional.

      Syntax:

          try {<statement list>}
          catch [[<error type]] {<statement list>}
          finally {<statement list>}

      Until
      -----

      Used in a Do statement as a looping construct where the statement list is
      executed at least one time.

      Syntax:

          do {<statement list>} until (<condition>)

      While
      -----

      Used in a Do statement as a looping construct where the statement list is
      executed at least one time.

      Syntax:

          do {<statement list>} while (<condition>)

SEE ALSO
     about_Escape_Characters
     about_Reserved_Words
     about_Special_Characters
     about_Wildcards


about_Line_Editing

TOPIC
    about_Line_Editing

SHORT DESCRIPTION
    Describes how to edit commands at the Windows PowerShell command prompt.

LONG DESCRIPTION
    The Windows PowerShell console has some useful features to help
    you to edit commands at the Windows PowerShell command prompt.

    Move Left and Right
        To move the cursor one character to the left, press the LEFT ARROW
        key. To move the cursor one word to the left, press CTRL+LEFT ARROW.
        To move the cursor one character to the right, press the RIGHT ARROW
        key. To move the cursor one word to the right, press CTRL+RIGHT ARROW.

    Line Start and End
        To move to the beginning of a line, press the HOME key. To move to the
        end of a line, press the END key.

    Delete Characters
        To delete the character in behind the cursor, press the BACKSPACE key.
        To delete the character in front of the cursor, press the DELETE key.

    Delete the Remainder of a Line
        To delete all the characters in the line after the cursor, press
        CTRL+END.

    Insert/Overstrike Mode
        To change to overstrike mode, press the INSERT key. To return to insert
        mode, press INSERT again.

    Tab Completion
        To complete a command, such as the name of a cmdlet, a cmdlet
        parameter, or a path, press the TAB key. If the first suggestion that
        is displayed is not what you want, press the TAB key again.

SEE ALSO
    about_Command_Syntax
    about_Path_Syntax


about_Locations

TOPIC
    about_Locations

SHORT DESCRIPTION
    Describes how to access items from the working location in Windows
    PowerShell.

LONG DESCRIPTION
    The current working location is the default location to which commands
    point. In other words, this is the location that Windows PowerShell uses
    if you do not supply an explicit path to the item or location that is
    affected by the command. In most cases, the current working location is
    a drive accessed through the Windows PowerShell FileSystem provider and,
    in some cases, a directory on that drive. For example, you might set your
    current working location to the following location:

        C:\Program Files\Windows PowerShell

    As a result, all commands are processed from this location unless
    another path is explicitly provided.

    Windows PowerShell maintains the current working location for each drive
    even when the drive is not the current drive. This allows you to access
    items from the current working location by referring only to the drive of
    another location. For example, suppose that your current working location
    is C:\Windows. Now, suppose you use the following command to change your
    current working location to the HKLM: drive:

        Set-Location HKLM:

    Although your current location is now the registry drive, you can still
    access items in the C:\Windows directory simply by using the C: drive,
    as shown in the following example:

        Get-ChildItem C:

    Windows PowerShell remembers that your current working location for that
    drive is the Windows directory, so it retrieves items from that directory.
    The results would be the same if you ran the following command:

        Get-ChildItem C:\Windows

    In Windows PowerShell, you can use the Get-Location command to determine
    the current working location, and you can use the Set-Location command to
    set the current working location. For example, the following command sets
    the current working location to the Windows directory of the C: drive:

        Set-Location c:\windows

    After you set the current working location, you can still access items
    from other drives simply by including the drive name (followed by a
    colon) in the command, as shown in the following example:

        Get-ChildItem HKLM :\software

    The example command retrieves a list of items in the Software container
    of the HKEY Local Machine hive in the registry.

    Windows PowerShell also allows you to use special characters to represent
    the current working location and its parent location. To represent the
    current working location, use a single period. To represent the parent of
    the current working location, use two periods. For example, the following
    specifies the System subdirectory in the current working location:

        Get-ChildItem .\system

    If the current working location is C:\Windows, this command
    returns a list of all the items in C:\Windows\System. However, if you
    use two periods, the parent directory of the current working
    directory is used, as shown in the following example:

        Get-ChildItem ..\"program files"

    In this case, Windows PowerShell treats the two periods as the C: drive,
    so the command retrieves all the items in the C:\Program Files directory.

    A path beginning with a slash identifies a path from the root of the
    current drive. For example, if your current working location is
    C:\Program Files\Windows PowerShell, the root of your drive is C.
    Therefore, the following command lists all items in the C:\Windows
    directory:

        Get-ChildItem \windows

    If you do not specify a path beginning with a drive name, slash, or
    period when supplying the name of a container or item, the
    container or item is assumed to be located in the current working
    location. For example, if your current working location is C:\Windows,
    the following command returns all the items in the C:\Windows\System
    directory:

        Get-ChildItem system

    If you specify a file name rather than a directory name, Windows
    PowerShell returns details about that file (assuming that file is located
    in the current working location).

SEE ALSO
    Set-Location
    about_Providers
    about_Path_Syntax


about_Logical_Operators

TOPIC
    about_Logical_Operators

SHORT DESCRIPTION
    Describes the operators that connect statements in Windows PowerShell.

LONG DESCRIPTION
    The Windows PowerShell logical operators connect expressions and
    statements, allowing you to use a single expression to test for multiple
    conditions.

    For example, the following statement uses the and operator and
    the or operator to connect three conditional statements. The statement is
    true only when the value of $a is greater than the value of $b, and
    either $a or $b is less than 20.

        ($a -gt $b) -and (($a -lt 20) -or ($b -lt 20))

    Windows PowerShell supports the following logical operators.

        Operator  Description                      Example
        --------  ------------------------------   ------------------------
        -and      Logical and. TRUE only when      (1 -eq 1) -and (1 -eq 2)
                  both statements are TRUE.         False

        -or       Logical or. TRUE when either     (1 -eq 1) -or (1 -eq 2)
                  or both statements are TRUE.     True

        -xor      Logical exclusive or. TRUE       (1 -eq 1) -xor (2 -eq 2)
                  only when one of the statements  False
                  is TRUE and the other is FALSE.

        -not      Logical not. Negates the         -not (1 -eq 1)
                  statement that follows it.       False

        !         Logical not. Negates the         !(1 -eq 1)
                  statement that follows it.       False
                  (Same as -not)

    Note: The previous examples also use the equal to comparison
          operator (-eq). For more information, see about_Comparison_Operators.
          The examples also use the Boolean values of integers. The integer 0
          has a value of FALSE. All other integers have a value of TRUE.

    The syntax of the logical operators is as follows:

        <statement> {-AND | -OR | -XOR} <statement>
        {! | -NOT} <statement>

    Statements that use the logical operators return Boolean (TRUE or FALSE)
    values.

    The Windows PowerShell logical operators evaluate only the statements
    required to determine the truth value of the statement. If the left operand
    in a statement that contains the and operator is FALSE, the right operand
    is not evaluated. If the left operand in a statement that contains
    the or statement is TRUE, the right operand is not evaluated. As a result,
    you can use these statements in the same way that you would use
    the If statement.

SEE ALSO
    about_Operators
    Compare-Object
    about_Comparison_operators
    about_If


about_Methods

TOPIC
    about_methods

SHORT DESCRIPTION
    Describes how to use methods to perform actions on objects in Windows
    PowerShell.

LONG DESCRIPTION
    Windows PowerShell uses structured collections of information, called
    objects, to represent the items in data stores or the state of the
    computer. For example, when you access a file in Windows PowerShell, you
    are not working with the actual file. Instead, you are working with a
    FileInfo object, a type of object that acts as the file's proxy.

    Most objects include methods. A method is a set of instructions that
    specify a particular action you can take with that object. For instance,
    the FileInfo object includes a method called CopyTo, which allows you to
    copy the file represented by the object.

    To view a list of methods and method definitions associated with a
    particular object, you can use the Get-Member cmdlet. However, to use
    the cmdlet, the object must already exist in some form, either as
    represented through a variable, as an object created when you specify a
    command as an argument to the Get-Member command, or as an object
    passed down a pipeline. For example, suppose that the $a variable has
    been assigned a string value, which means that the variable is
    associated with a string object. To view a list of the object's
    methods, enter the following command at the Windows PowerShell command
    prompt:

        Get-Member -inputobject $a -membertype method

    If you want to see which methods and method definitions are associated
    with an object that is passed down the pipeline, you would use a
    Get-Member command within the pipeline, as shown in the following example:

        Get-ChildItem c:\final.txt | Get-Member -membertype method

    The most common way to invoke a method is to specify the method name
    after an object reference (such as a variable or expression). You must
    separate the object reference and the method with a period. Additionally,
    you must use parentheses immediately following the method name to enclose
    any arguments that should be passed to the method.

    If no arguments are being passed in a method signature, you must still
    use a set of empty parentheses.

    For example, the following command uses the GetType method to return the
    data type associated with the $a string object:

        $a.GetType()

    The GetType method will return the data type for any object, and a
    variable always represents an object. The type of object depends on the
    type of data stored within that variable.

    Every action you take in Windows PowerShell is associated with objects,
    whether you are declaring a variable or combining commands into a pipeline.
    As a result, methods can be used in a variety of situations. For example,
    you can use a method to take an action on a property value, as shown in
    the following command:

        (Get-ChildItem c:\final.txt).name.ToUpper()

    In this case, the object on which the ToUpper method is being invoked is
    the string object associated with the name property. (Note that the
    Final.txt file must exist on the root of the C: drive for this example
    to work.) The name property is actually a property of the FileInfo object
    returned by the Get-ChildItem command. This demonstrates not only the
    object-oriented nature of Windows PowerShell, but shows how methods can be
    called on any accessible object.

    You can achieve the same results as the last example by using a
    variable to store the Get-ChildItem command output, as shown in the
    following example:

        $a = (Get-ChildItem c:\final.txt).name
        $a.ToUpper()

    The command again uses the ToUpper method of the string object
    associated with the variable, which contains the file name returned by
    the Get-ChildItem command.

    In some cases, a method requires an argument to direct the action of
    that method. For example, the FileInfo object includes the MoveTo
    method, which provides a way to move a file from one location to
    another. The method requires an argument that specifies the target
    location for the file. The following command demonstrates how to
    include that argument:

        (Get-ChildItem c:\final.txt).MoveTo("c:\techdocs\final.txt")

    The Get-ChildItem command returns a FileInfo object for the Final.txt
    file and then uses the MoveTo method of that object to initiate the
    action and to specify the file's new location.

    To determine the arguments associated with a method, review the
    corresponding method definition. A method definition contains one or
    more method signatures (also known as overloads in the Microsoft
    .NET Framework). A method signature contains the name of a method and zero
    or more parameters that you must supply when you call the method. Each
    method signature is separated from the prior signature with a comma in the
    Get-Member cmdlet display. For example, the CopyTo method of the
    FileInfo class contains the following two method signatures:

        1. CopyTo(String destFileName)
        2. CopyTo(String destFileName, Boolean overwrite)

    The first method signature takes the destination file name (including
    the path) in which to copy the source file. In the following example,
    the first CopyTo method is used to copy Final.txt to the C:\Bin
    directory:

        (Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt")

    If the file already exists in the destination location, the CopyTo
    method fails, and Windows PowerShell reports the following error:

        Exception calling "CopyTo" with "1" argument(s): "The file
        'c:\bin\final.txt' already exists.".

    In the second method signature, you pass the destination file name just
    as you did in the first case, but you also pass a Boolean value to
    specify whether you want an existing file of the same name in the
    destination location to be overwritten, as the following example shows:

        (Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt", $true)

    When you pass the Boolean value, you must use the $True variable, which
    is created automatically by Windows PowerShell. The $True variable
    contains the "true" Boolean value. (As you would expect, the $False
    variable contains the "false" Boolean value.)

SEE ALSO
    about_Objects
    Get-Member


about_Modules

TOPIC
    about_Modules

SHORT DESCRIPTION
    Explains how to install, import, and use Windows PowerShell modules.

LONG DESCRIPTION
    A module is a package that contains Windows PowerShell commands, such as
    cmdlets, providers, functions, variables, and aliases.

    People who write commands can use modules to organize their commands and
    share them with others. People who receive modules can add the commands
    in the modules to their Windows PowerShell sessions and use them just like
    the built-in commands.

    This topic explains how to use Windows PowerShell modules. For information
    about how to write Windows PowerShell modules, see "Writing a Windows
    PowerShell Module" in the MSDN (Microsoft Developer Network) library
    at http://go.microsoft.com/fwlink/?LinkId=144916.

 HOW TO USE A MODULE
    To use a module, perform the following tasks:

        1. Install the module. (This is often done for you.)
        2. Import the module into your Windows PowerShell session.
        3. Find the commands that the module added.
        4. Use the commands that the module added.

    This topic explains how to perform these tasks. It also includes
    other useful information about managing modules.

 HOW TO INSTALL A MODULE
    If you receive a module as a folder with files in it, you need
    to install it on your computer before you can import it into Windows
    PowerShell.

    Most modules are installed for you. Windows PowerShell comes with
    several pre-installed modules. In Windows Server 2008 R2, the
    Add Features Wizard in Server Manager automatically installs the
    feature modules that you select. Many other modules come in an
    installer or Setup program that installs the module.

    To install a module folder:

        1. Create a Modules directory for the current user if one does
           not exist.

           To create a Modules directory, type:

               new-item -type directory -path $home\Documents\WindowsPowerShell\Modules

        2. Copy the entire module folder into the Modules directory.

           You can use any method to copy the folder, including Windows
           Explorer and Cmd.exe, as well as Windows PowerShell.

           In Windows PowerShell use the Copy-Item cmdlet. For example, to copy the
           MyModule folder from C:\ps-test\MyModule to the Modules directory, type:

               copy-item -path c:\ps-test\MyModule -dest $home\Documents\WindowsPowerShell\Modules

    You can install a module in any location, but installing your modules in a
    default module location makes them easier to manage. For more information about
    the default module locations, see the "Module Locations and PSModulePath" section.

 HOW TO FIND INSTALLED MODULEs
     When a module is installed, you can import it into your Windows
     PowerShell session.

     To find modules that are installed in a default module location,
     at the Windows PowerShell prompt, type:

         get-module -listAvailable

     To find the modules that have already been imported into your session,
     at the Windows PowerShell prompt, type:

         get-module

     For more information about the Get-Module cmdlet, see Get-Module.

 HOW TO IMPORT A MODULE
    To use the commands in a module, import the module into a
    Windows PowerShell session.

    To import modules from a default module location into the
    current session, use the following command format.

        import-module <module-name>

    For example, the following command imports the BitsTransfer module
    into the current session.

        import-module BitsTransfer

    To import a module that is not in a default module location, use
    the fully qualified path to the module folder in the command.

    For example, to add the TestCmdlets module in the C:\ps-test directory
    to your session, type:

        import-module c:\ps-test\TestCmdlets

    For more information about adding modules to your session, see
    Import-Module.

 HOW TO IMPORT ALL MODULES INTO YOUR WINDOWS POWERSHELL SESSION
    In Windows 7 and Windows Server 2008 R2, the "Import all modules"
    task opens a Windows PowerShell session that includes all the
    available Windows PowerShell modules and snap-ins.

    To start a Windows PowerShell session with all the available Windows
    PowerShell modules and snap-ins, use the following procedure.

    -- Right-click the Windows PowerShell icon in the taskbar, and then click
       "Import all modules".

    Note: In Windows Server 2008 R2, the Windows PowerShell icon is pinned to
          the taskbar by default. However, you must start Windows PowerShell
          one time to make the "Import all modules" task appear.

    In other versions of Windows, to import all the available modules into your
    session, at the Windows PowerShell prompt, type:

        get-module -listAvailable | import-module

 HOW TO FIND THE COMMANDS IN A MODULE
    After you import a module into your Windows PowerShell session, you can
    use the commands in the module.

    To find the commands that a module added, at the Windows PowerShell prompt,
    type:

        get-command -module <module-name>

    For example, to find the commands that the BitsTransfer module adds, type:

        get-command -module BitsTransfer

    For more information about the Get-Command cmdlet, see Get-Command.

 HOW TO FIND HELP FOR THE COMMANDS IN A MODULE
    If the module contains Help topics for the commands that it exports,
    the Get-Help cmdlet will display the Help topics. Use the same command
    format that you would use for any Help topic in Windows PowerShell.

    To find the Help topic for the commands in a module, at the Windows
    PowerShell prompt, type:

        get-help <command-name>

    For more detailed Help, type:

        get-help <command-name> -detailed

    For example, to find detailed Help for the Start-BitsTransfer cmdlet,
    type:

        get-help Start-BitsTransfer -detailed

    For more information about the Get-Help module, see Get-Help.

 HOW TO REMOVE A MODULE
    When you remove a module, the commands that the module added are deleted
    from the session.

    To remove a module from your session, use the following command
    format.

        remove-module <module-name>

    For example, the following command removes the BitsTransfer module
    from the current session.

        remove-module BitsTransfer

    Removing a module reverses the operation of importing a module. Removing
    a module does not uninstall the module. For more information about the
    Remove-Module cmdlet, see Remove-Module.

 HOW TO IMPORT A MODULE INTO EVERY SESSION
    The Import-Module command imports modules into your current Windows
    PowerShell session. This command affects only the current session.

    To import a module into every Windows PowerShell session that you
    start, add the Import-Module command to your Windows PowerShell
    profile.

    For more information about profiles, see about_Profiles.

 MODULE LOCATIONS AND PSMODULEPATH
    There are two default locations for Windows PowerShell modules, one for
    the system and one for the current user.

        System:        $pshome\Modules
                           (%windir%\System32\WindowsPowerShell\v1.0\Modules)

        Current user:  $home\Documents\WindowsPowerShell\Modules
                           (%UserProfile%\Documents\WindowsPowerShell\Modules)

                       - or -

                       $home\My Documents\WindowsPowerShell\Modules
                           (%UserProfile%\My Documents\WindowsPowerShell\Modules)

        Note: In Windows Vista, Windows Server 2008, and later versions of
              Windows, to add or change files in the %Windir%\System32 directory,
              start Windows PowerShell with the "Run as administrator" option.

    You can change the default module locations on your system by changing the
    value of the PSModulePath environment variable ($env:psmodulepath). The
    PSModulePath environment variable is modeled on the Path environment variable
    and has the same format.

    To view the default module locations, type:

        $env:psmodulepath

    To add a default module location, use the following command format.

        $env:psmodulepath = $env:psmodulepath + ";<path>"

    The semi-colon (;) in the command separates the new path from the
    path that precedes it in the list.

    For example, to add the "C:\ps-test\Modules" directory, type:

        $env:psmodulepath + ";c:\ps-test\Modules"

    When you add a path to PSModulePath, Get-Module and Import-Module
    commands include modules in that path.

    The value that you set affects only the current session. To make the
    change persistent, add the command to your Windows PowerShell profile
    or use the System item in Control Panel to change the value of the
    PSModulePath environment variable in the registry.

    For more information about the PSModulePath variable, see
    about_Environment_Variables.

 MODULES AND NAME CONFLICTS
    Name conflicts occur when more than one command in the session
    has the same name. Importing a module causes a name conflict when
    commands in the module have the same names as commands or items
    in the session.

    Name conflicts can result in commands being hidden or replaced.

        -- Hidden. A command is hidden when it is not the command
           that runs when you type the command name, but you can run it
           by using another method, such as by qualifying the command
           name with the name of the module or snap-in in which it
           originated.

        -- Replaced. A command is replaced when you cannot run it because
           it has been overwritten by a command with the same name. Even
           when you remove the module that caused the conflict, you cannot
           run a replaced command unless you restart the session.

    Import-Module might add commands that hide and replace commands in the
    current session. Also, commands in your session can hide commands that
    the module added.

    To prevent name conflicts, use the Prefix parameter of Import-Command
    to create unique names for the imported commands.

    You can also use the Alias, Cmdlet, Function, and Variable parameters
    of Import-Module to select only the commands that you want to import,
    and you can exclude commands that cause name conflicts in your session.

    Even if a command is hidden, you can run it by qualifying the command
    name with the name of the module or snap-in in which it originated.

    The Windows PowerShell command precedence rules determine which command
    runs when the session includes commands with the same name.

    For example, when a session includes a function and a cmdlet with the same
    name, Windows PowerShell runs the function by default. When the session
    includes commands of the same type with the same name, such as two cmdlets
    with the same name, by default, it runs the most recently added command.

    For more information, including an explanation of the precedence rules and
    instructions for running hidden commands, see about_Command_Precedence.

 MODULES AND SNAP-INS
    You can add commands to your session from modules and snap-ins. Modules
    can add all types of commands, including cmdlets, providers, and functions,
    and items, such as variables, aliases, and Windows PowerShell drives.
    Snap-ins can add only cmdlets and providers.

    In fact, although you can add functions, aliases, variables, and drives
    to your session by typing them or running a script that adds them, all
    the cmdlets and providers in your session come from a module or a snap-in.

    Before removing a module or snap-in from your session, use the following
    commands to determine which commands will be removed.

    To find the source of a cmdlet in your session, use the following command
    format:

        get-command <cmdlet-name> | format-list -property verb, noun, pssnapin, module

    For example, to find the source of the Get-Date cmdlet, type:

        get-command get-date | format-list -property verb, noun, pssnapin, module

    For more information about Windows PowerShell snap-ins, see about_PSSnapins.

SEE ALSO
    about_Command_Precedence
    about_PSSnapins
    Get-Command
    Get-Help
    Get-Module
    Import-Module
    Remove-Module


about_Objects

TOPIC
    about_Objects

SHORT DESCRIPTION
    Provides essential information about objects in Windows PowerShell.

LONG DESCRIPTION
    Every action you take in Windows PowerShell occurs within the context of
    objects. As data moves from one command to the next, it moves as one or
    more identifiable objects. An object, then, is a collection of data that
    represents an item in a namespace. An object is made up of three types
    of data: the object's type, its methods, and its properties.

    The data about an object's type provides details about what kind of
    object it is. For example, an object that represents a file is a
    FileInfo object.

    An object's method is an action that you can perform on the item that
    the object represents. For instance, a FileInfo object includes a
    method that you can use to cause the file to be copied. That is, when
    you invoke the copy method of the object, the file that the object
    represents is copied.

    An object's property is information about the state of that object. For
    example, a FileInfo object includes the length property, which
    specifies the size of the file represented by the object.

    When working with objects, you can use their methods and properties in
    your commands to take specific actions and manipulate data. This is
    especially useful when you combine multiple commands into a single
    pipeline.

    When commands are combined in a pipeline, they pass information to each
    other as objects. When the first command runs, it sends one or more
    objects down the pipeline to the second command. The second command
    receives the objects from the first command, processes the objects, and
    then passes new or revised objects to the next command in the pipeline.
    This continues until all commands in the pipeline run.

    The following example demonstrates how objects are passed from one
    command to the next:

        Get-ChildItem c: | where {$_.PsIsContainer -eq $false} |
        Format-List

    The first command (Get-ChildItem c:) returns an object for each item in
    the root directory of the file system. Those objects are passed down
    the pipeline to the second command (where {$_.PsIsContainer -eq
    $false}). The second command uses the PsIsContainer property of the
    object to filter the data from the input objects so that no directories
    (containers) are returned. The command then passes the information as
    objects to the third command (Format-List), which displays the contents
    of each piped object in a list format.

SEE ALSO
    about_Methods
    about_Properties
    about_Pipelines
    Get-Member


about_Operators

TOPIC
    about_Operators

SHORT DESCRIPTION
    Describes the operators that are supported by Windows PowerShell.

LONG DESCRIPTION
    An operator is a language element that you can use in a command or
    expression. Windows PowerShell supports several types of operators to
    help you manipulate values.

  Arithmetic Operators
      Use arithmetic operators (+, -, *, /, %) to calculate values in a command
      or expression. With these operators, you can add, subtract, multiply, or
      divide values, and calculate the remainder (modulus) of a division
      operation.

      You can also use arithmetic operators with strings, arrays, and hash
      tables. The addition operator concatenates elements. The multiplication
      operator returns the specified number of copies of each element.

      For more information, see about_Arithmetic_Operators.

  Assignment Operators
      Use assignment operators (=, +=, -=, *=, /=, %=) to assign one or more
      values to variables, to change the values in a variable, and to append
      values to variables. You can also cast the variable as any Microsoft .NET
      Framework data type, such as string or DateTime, or Process variable.

      For more information, see about_Assignment_Operators.

  Comparison Operators
      Use comparison operators (-eq, -ne, -gt, -lt, -le, -ge) to compare values
      and test conditions. For example, you can compare two string values to
      determine whether they are equal.

      The comparison operators include the match operators (-match, -notmatch)
      to find patterns using regular expressions; the replace operator
      (-replace), which uses regular expressions to change input values; and
      the like operators (-like, -notlike), which find patterns using wildcard
      characters (*).

      They also include the bitwise operators (-bAND, -bOR, -bXOR, -bNOT) to
      manipulate the bit patterns in values.

    For more information, see about_Comparison_Operators

  Logical Operators
      Use logical operators (-and, -or, -xor, -not, !) to connect conditional
      statements into a single complex conditional. For example, you can use a
      logical -and operator to create an object filter with two different
      conditions.

      For more information, see about_Logical_Operators.

  Redirection Operators
      Use redirection operators (>, >>, 2>, 2>, and 2>&1) to send the output of
      a command or expression to a text file. The redirection operators work
      like the Out-File cmdlet (without parameters) but they also let you
      redirect error output to specified files. You can also use the Tee-Object
      cmdlet to redirect output.

      For more information, see about_Redirection.

  Split and Join Operators
      The -split and -join operators divide and combine substrings. The -split
      operator splits a string into substrings. The -join operator concatenates
      multiple strings into a single string.

      For more information, see about_Split and about_Join.

  Type Operators
      Use the type operators (-is, -isnot, -as) to find or change the .NET
      Framework type of an object.

      For more information, see about_Type_Operators.

  Unary Operators
      Use unary operators to increment or decrement variables or object
      properties and to set integers to positive or negative numbers. For
      example, to increment the variable $a from 9 to 10, you type $a++.

  Special Operators
      Use special operators to perform tasks that cannot be performed by the
      other types of operators. For example, special operators allow you to
      perform operations such as running commands and changing a value's data
      type.

      &  Call operator
        Description: Runs a command, script, or script block. Because the call
        operator does not parse, it cannot interpret command parameters. The
        call operator, also known as the "invocation operator, indicates that
        the value it precedes is a command. This enables you to run commands
        stored in variables and represented by strings. Examples:

            & "new cmdlet"
            $c = "get-executionpolicy"
            & $c

      . Property dereference operator
        Description: Accesses the properties and methods of an object.
        Examples:

            $myString.length
            $myString.substring(1,3)

      . dot sourcing operator
        Description: Runs a script so that the items in the script are part
        of the calling scope. For more information, see about_Scope. Example:

            . c:\scripts.sample.ps1

        Note: The dot (.) symbol is also used as the parent directory symbol,
              as in this example:

                .\sample.ps1

              This command runs the sample.ps1 script, but not as part of the
              calling scope.

      :: Static member operator
        Description: Calls the static properties operator and methods of a .NET
        Framework class. To find the static properties and methods of an
        object, use the Static parameter of the Get-Member cmdlet. Example:

            [datetime]::now

      .. Range operator
        Description: Represents the sequential integers in an integer array,
        given an upper and lower boundary. Examples:

            1..10
            10..1
            foreach ($a in 1..$max) {write-host $a}

      -f Format operator
        Description: Formats strings by using the format method of string
        objects. Enter the format string on the left side of the operator
        and the objects to be formatted on the right side of the operator.
        Examples:

            C:\PS> "{0} {1,-10} {2:N}" -f
            C:\PS> 1,"hello",[math]::pi
            1 hello 3.14

      $( ) Subexpression operator
        Description: Returns the result of one or more statements. For a
        single result, returns a scalar. For multiple results, returns an
        array. Examples:

            $($x * 23)
            $(Get-WMIObject win32_Directory)

      @( ) Array subexpression operator
        Description: Returns the result of one or more statements as an array.
        If there is only one item, the array has only one member. Example:

            @(Get-WMIObject win32_logicalDisk)

      , operator
        Description: As a binary operator, the comma creates an array. As a
        unary operator, the comma creates an array with one member. Place the
        comma before the member. Examples:

            $myArray = 1,2,3
            $SingleArray = ,1

SEE ALSO
    about_Arithmetic_Operators
    about_Assignment_Operators
    about_Comparison_Operators
    about_Logical_Operators
    about_Type_Operators
    about_Split
    about_Join
    about_Redirection


about_Parameters

TOPIC
    about_Parameters

SHORT DESCRIPTION
    Describes how to work with cmdlet parameters in Windows PowerShell.

LONG DESCRIPTION
    Most Windows PowerShell cmdlets and functions rely on parameters to allow
    users to select options or provide input. The parameters follow the cmdlet
    or function name and typically have the following form:

        -<parameter_name> <parameter_value>

    The name of the parameter is preceded by a hyphen (-), which signals to
    Windows PowerShell that the word following the hyphen is a parameter and
    not a value being passed to the cmdlet or function. Not all parameters
    require a value, and not all parameter names must be specified. In some
    cases, the parameter name is implied and does not need to be included in
    the command.

    The type of parameters and the requirements for those parameters vary by
    cmdlet and by function from cmdlet to cmdlet. To find information about the
    parameters of a cmdlet, use the Get-Help cmdlet. For example, to find
    information about the parameters of the Get-ChildItem cmdlet, type:

        get-help get-childitem

    To find information about the parameters of a function, review the
    parameter definitions. Parameters are defined either after the function
    name or inside the body of the function, using the Param keyword. For more
    information, see about_Functions.

    Some functions also contain comment-based Help about parameters. Use the
    Get-Help cmdlet with these functions. For more information, see the help
    topic for Get-Help and about_Comment_Based_Help.

    The Get-Help Cmdlet returns various details about the cmdlet or function,
    including a description of the cmdlet or function, the command syntax,
    information about the parameters, and examples showing how to use the
    cmdlet or function.

    You can also use the Parameter parameter of the Get-Help cmdlet or function
    to find information about a particular parameter. Or, you can use the
    wildcard character (*) with the Parameter parameter to find information
    about all the parameters of the cmdlet or function. For example, the
    following command gets information about all the parameters of the
    Get-Member cmdlet or function:

        get-help get-member -parameter *

    This information includes the details you need to know to use the
    parameter. For example, the Help topic for the Get-ChildItem cmdlet
    includes the following details about its Path parameter:

        -path <string[]>
            Specifies a path of one or more locations. Wildcard characters are
            permitted. The default location is the current directory (.).

        Required?                    false
        Position?                    1
        Default value                Current directory
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  true

    The parameter information includes the parameter syntax,
    a description of the parameter, and the parameter attributes.
    The following sections describe the parameter attributes.

  Parameter Required?
    This setting indicates whether the parameter is mandatory, that
    is, whether all commands that use this cmdlet must include this
    parameter. When the value is "True" and the parameter is missing
    from the command, Windows PowerShell prompts you for a value for
    the parameter.

  Parameter Position?
    This setting indicates whether you can supply a parameter's value
    without preceding it with the parameter name. If set to "0" or "named,"
    a parameter name is required. This type of parameter is referred to as
    a named parameter. A named parameter can be listed in any position
    after the cmdlet name.

    If the "Parameter position?" setting is set to an integer other than 0,
    the parameter name is not required. This type of parameter is referred
    to as a positional parameter, and the number indicates the position
    in which the parameter must appear in relation to other positional
    parameters. If you include the parameter name for a positional
    parameter, the parameter can be listed in any position after the
    cmdlet name.

    For example, the Get-ChildItem cmdlet has Path and Exclude parameters.
    The "Parameter position?" setting for Path is 1, which means that it
    is a positional parameter. The "Parameter position?" setting for Exclude
    is 0, which means that it is a named parameter.

    This means that Path does not require the parameter name, but its
    parameter value must be the first or only unnamed parameter value
    in the command. However, because the Exclude parameter is a named
    parameter, you can place it in any position in the command.

    As a result of the "Parameter position?" settings for these two
    parameters, you can use any of the following commands:

        Get-ChildItem -path c:\techdocs -exclude *.ppt
        Get-ChildItem c:\techdocs -exclude *.ppt
        Get-ChildItem -exclude *.ppt -path c:\techdocs
        Get-ChildItem -exclude *.ppt c:\techdocs

    If you were to include another positional parameter without including
    the parameter name, that parameter would have to be placed in the order
    specified by the "Parameter position?" setting.

  Parameter Type
    This setting specifies the Microsoft .NET Framework type of the parameter
    value. For example, if the type is Int32, the parameter value must be an
    integer. If the type is string, the parameter value must be a
    character string. If the string contains spaces, the value must be
    enclosed in quotation marks, or the spaces must be preceded by the
    escape character (`).

  Default Value
    This setting specifies the value that the parameter will assume
    if no other value is provided. For example, the default value of
    the Path parameter is often the current directory. Required
    parameters never have a default value. For many optional parameters,
    there is no default because the parameter has no effect if it is
    not used.

  Accepts Multiple Values?
    This setting indicates whether a parameter accepts multiple
    parameter values. When a parameter accepts multiple values,
    you can type a comma-separated list as the value of the parameter
    in the command, or save a comma-separated list (an array) in a
    variable, and then specify the variable as the parameter value.

    For example, the ServiceName parameter of the Get-Service
    cmdlet accepts multiple values. The following commands are both valid:

        get-service -servicename winrm, netlogon

        $s = "winrm", "netlogon"
        get-service -servicename $s

  Accepts Pipeline Input?
    This setting indicates whether you can use the pipeline operator
    (|) to send a value to the parameter.

    Value                    Description
    -----                    -----------
    False                    Indicates that you cannot pipe a value to the
                             parameter.

    True (by Value)          Indicates that you can pipe any value to the
                             parameter, just so the value has the .NET
                             Framework type specified for the parameter or the
                             value can be converted to the specified .NET
                             Framework type.

                             When a parameter is "True (by Value)", Windows
                             PowerShell tries to associate any piped values
                             with that parameter before it tries other methods
                             to interpret the command.

    True (by Property Name)  Indicates that you can pipe a value to the
                             parameter, but the .NET Framework type of the
                             parameter must include a property with the same
                             name as the parameter.

                             For example, you can pipe a value to a Name
                             parameter only when the value has a property
                             called "Name".

  Accepts Wildcard Characters?
    This setting indicates whether the parameter's value can contain
    wildcard characters so that the parameter value can be matched to more
    than one existing item in the target container.

  Common Parameters
    Common parameters are parameters that you can use with any cmdlet.
    For more information, about common parameters, type:

        help about_commonparameters

SEE ALSO
    about_Command_syntax
    about_Comment_Based_Help
    about_Functions_Advanced
    about_Pipelines
    about_Wildcards


about_Parsing

TOPIC
    about_parsing

SHORT DESCRIPTION
    Describes how Windows PowerShell parses commands.

LONG DESCRIPTION
    When you enter a command at the command prompt, Windows PowerShell
    breaks the command text into a series of segments called tokens
    and then determines how to interpret each one. For example, Windows
    PowerShell breaks the following command into two tokens, "Write-Host"
    and "book", and interprets each token separately:

        Write-Host book

    When processing a command, the Windows PowerShell parser operates
    in expression mode or in argument mode:

        - In expression mode, character string values must be contained in
          quotation marks. Numbers not enclosed in quotation marks are treated
          as numerical values (rather than as a series of characters).

        - In argument mode, each value is treated as an expandable string
          unless it begins with one of the following special characters: dollar
          sign ($), at sign (@), single quotation mark ('), double quotation
          mark ("), or an opening parenthesis (().

    If preceded by one of these characters, the value is treated as a value
    expression.

    The following table provides several examples of commands processed in
    expression mode and argument mode and the results produced by those
    commands.

    Example            Mode         Result
    ------------------ ----------   ----------------
    2+2                Expression   4 (integer)
    Write-Output 2+2   Argument     "2+2" (string)
    Write-Output (2+2) Expression   4 (integer)
    $a = 2+2           Expression   $a = 4 (integer)
    Write-Output $a    Expression   4 (integer)
    Write-Output $a/H  Argument     "4/H" (string)

    Every token can be interpreted as some kind of object type, such
    as Boolean or string. Windows PowerShell attempts to determine the
    object type from the expression. The object type depends on the
    type of parameter a command expects and on whether Windows PowerShell
    knows how to convert the argument to the correct type. The
    following table shows several examples of the types assigned to
    values returned by the expressions.

    Example            Mode         Result
    ------------------ ----------   ---------------
    Write-Output !1    argument     "!1" (string)
    Write-Output (!1)  expression   False (Boolean)
    Write-Output (2)   expression   2 (integer)

SEE ALSO
    about_Command_Syntax


about_Path_Syntax

TOPIC
    about_Path_Syntax

SHORT DESCRIPTION
    Describes the full and relative path name formats in Windows PowerShell.

LONG DESCRIPTION
    All items in a data store accessible through a Windows PowerShell provider
    can be uniquely identified by their path names. A path name is a
    combination of the item name, the container and subcontainers in which
    the item is located, and the Windows PowerShell drive through which the
    containers are accessed.

    In Windows PowerShell, path names are divided into one of two types: fully
    qualified and relative. A fully qualified path name consists of all
    elements that make up a path. The following syntax shows the elements in
    a fully qualified path name:

        [<provider>::]<drive>:[\<container>[\<subcontainer>...]]\<item>

    The <provider> placeholder refers to the Windows PowerShell provider
    through which you access the data store. For example, the FileSystem
    provider allows you to access the files and directories on your computer.
    This element of the syntax is optional and is never needed because the
    drive names are unique across all providers.

    The <drive> placeholder refers to the Windows PowerShell drive that is
    supported by a particular Windows PowerShell provider. In the case of the
    FileSystem provider, the Windows PowerShell drives map to the Windows
    drives that are configured on your system. For example, if your system
    includes an A: drive and a C: drive, the FileSystem provider creates the
    same drives in Windows PowerShell.

    After you have specified the drive, you must specify any containers and
    subcontainers that contain the item. The containers must be specified
    in the hierarchical order in which they exist in the data store. In
    other words, you must start with the parent container, then the child
    container in that parent container, and so on. In addition, each
    container must be preceded by a backslash. (Note that Windows PowerShell
    allows you to use forward slashes for compatibility with other
    powershells.)

    After the container and subcontainers have been specified, you must
    provide the item name, preceded by a backslash. For example, the fully
    qualified path name for the Shell.dll file in the C:\Windows\System32
    directory is as follows:

        C:\Windows\System32\Shell.dll

    In this case, the drive through which the containers are accessed is
    the C: drive, the top-level container is Windows, the subcontainer is
    System32 (located within the Windows container), and the item is Shell.dll.

    In some situations, you do not need to specify a fully qualified path
    name and can instead use a relative path name. A relative path name is
    based on the current working location. Windows PowerShell allows you to
    identify an item based on its location relative to the current working
    location. You can specify relative path names by using special characters.
    The following table describes each of these characters and provides
    examples of relative path names and fully qualified path names. The
    examples in the table are based on the current working directory being
    set to C:\Windows.

    Symbol Description                Relative path    Fully qualified path
    ------ -------------------------- ---------------- --------------------
    .      Current working location   .\System         c:\Windows\System
    ..     Parent of current working  ..\Program Files c:\Program Files
           location
    \      Drive root of current      \Program Files   c:\Program Files
           working location
    [none] No special characters      System           c:\Windows\System

    When using a path name in a command, you enter that name in the same
    way whether you use a fully qualified path name or a relative one. For
    example, suppose that your current working directory is C:\Windows. The
    following Get-ChildItem command retrieves all items in the C:\Techdocs
    directory:

        Get-ChildItem \techdocs

    The backslash indicates that the drive root of the current working
    location should be used. Because the working directory is C:\Windows,
    the drive root is the C: drive. Because the techdocs directory is located
    off the root, you need to specify only the backslash.

    You can achieve the same results by using the following command:

        Get-ChildItem c:\techdocs

    Regardless of whether you use a fully qualified path name or a relative
    path name, a path name is important not only because it locates an item
    but also because it uniquely identifies the item even if that item
    shares the same name as another item in a different container.

    For instance, suppose that you have two files that are each named
    Results.txt. The first file is in a directory named C:\Techdocs\Jan,
    and the second file is in a directory named C:\Techdocs\Feb. The path
    name for the first file (C:\Techdocs\Jan\Results.txt) and the path name
    for the second file (C:\Techdocs\Feb\Results.txt) allow you to clearly
    distinguish between the two files.

SEE ALSO
    about_Locations


about_Pipelines

TOPIC
    about_pipelines

SHORT DESCRIPTION
    Combining commands into pipelines in the Windows PowerShell

LONG DESCRIPTION
    A pipeline is a series of commands connected by pipeline operators
   (|)(ASCII 124). Each pipeline operator sends the results of the preceding
    command to the next command.

    You can use pipelines to send the objects that are output by one command
    to be used as input to another command for processing. And you can send the
    output of that command to yet another command. The result is a very powerful
    command chain or "pipeline" that is comprised of a series of simple commands.

    For example,

    Command-1 | Command-2 | Command-3

    In this example, the objects that Command-1 emits are sent to Command-2.
    Command-2 processes the objects and sends them to Command-3. Command-3 processes
    the objects and send them down the pipeline. Because there are no more commands in
    the pipeline, the results are displayed at the console.

    In a pipeline, the commands are processed from left to right in the order
    that they appear. The processing is handled as a single operation and
    output is displayed as it is generated.

    Here is a simple example. The following command gets the Notepad process
    and then stops it.

         get-process notepad | stop-process

    The first command uses the Get-Process cmdlet to get an object representing
    the Notepad process. It uses a pipeline operator (|) to send the process object
    to the Stop-Process cmdlet, which stops the Notepad process. Notice that the
    Stop-Process command does not have a Name or ID parameter to specify the process,
    because the specified process is submitted through the pipeline.

    Here is a practical example. This command pipeline gets the text files in the
    current directory, selects only the files that are more than 10,000 bytes long,
    sorts them by length, and displays the name and length of each file in a table.

        Get-ChildItem -path *.txt | Where-Object {$_.length -gt 10000} |
        Sort-Object -property Length | Format-Table -property name, length

    This pipeline is comprised of four commands in the specified order. The command
    is written horizontally, but we will show the process vertically in the following
    graphic.

       Get-ChildItem -path *.txt

                  |
                  |   (FileInfo objects )
                  |   (    .txt         )
                  |
                  V

       Where-Object {$_.length -gt 10000}

                  |
                  |   (FileInfo objects )
                  |   (    .txt         )
                  |   ( Length > 10000  )
                  |
                  V

       Sort-Object -property Length

                  |
                  |   (FileInfo objects  )
                  |   (    .txt          )
                  |   ( Length > 10000   )
                  |   ( Sorted by length )
                  |
                  V

       Format-Table -property name, length

                  |
                  |   (FileInfo objects     )
                  |   (    .txt             )
                  |   ( Length > 10000      )
                  |   ( Sorted by length    )
                  |   (Formatted in a table )
                  |
                  V
        Name                       Length
        ----                       ------
        tmp1.txt                    82920
        tmp2.txt                   114000
        tmp3.txt                   114000

USING PIPELINES

    The Windows PowerShell cmdlets were designed to be used in pipelines. For example,
    you can usually pipe the results of a Get cmdlet to an action cmdlet (such as a Set,
    Start, Stop, or Rename cmdlet) for the same noun.

    For example, you can pipe any service from the Get-Service cmdlet to the Start-Service
    or Stop-Service cmdlets (although disabled services cannot be restarted in this way).

    This command pipeline starts the WMI service on the computer:

    get-service wmi | start-service

    The cmdlets that get and set objects of the Windows PowerShell providers, such as the
    Item and ItemProperty cmdlets, are also designed to be used in pipelines.

    For example, you can pipe the results of a Get-Item or Get-ChildItem command in the
    Windows PowerShell registry provider to the New-ItemProperty cmdlet. This command adds
    a new registry entry, NoOfEmployees, with a value of 8124, to the MyCompany registry key.

       get-item -path HKLM:\Software\MyCompany | new-Itemproperty -name NoOfEmployees -value 8124

    Many of the utility cmdlets, such as Get-Member, Where-Object, Sort-Object, Group-Object,
    and Measure-Object are used almost exclusively in pipelines. You can pipe any objects to
    these cmdlets.

    For example, you can pipe all of the processes on the computer to the Sort-Object command
    and have them sorted by the number of handles in the process.

    get-process | sort-object -property handles

    Also, you can pipe any objects to the formatting cmdlets, such as Format-List and
    Format-Table, the Export cmdlets, such as Export-Clixml and Export-CSV, and the Out
    cmdlets, such as Out-Printer.

    For example, you can pipe the Winlogon process to the Format-List cmdlet to display all
    of the properties of the process in a list.

    get-process winlogon | format-list -property *

    With a bit of practice, you'll find that combining simple commands into pipelines
    saves time and typing, and makes your scripting more efficient.

HOW PIPELINES WORK

     When you "pipe" objects, that is send the objects in the output of one command to another
     command, Windows Powershell tries to associate the piped objects with one of the parameters
     of the receiving cmdlet.

     To do so, the Windows Powershell "parameter binding" component, which associates input objects
     with cmdlet parameters, tries to find a parameter that meets the following criteria:

     -- The parameter must accept input from a pipeline (not all do)
     -- The parameter must accept the type of object being sent or a type that the object
        can be converted to.
     -- The parameter must not already be used in the command.

     For example, the Start-Service cmdlet has many parameters, but only two of them, Name and InputObject
     accept pipeline input. The Name parameter takes strings and the InputObject parameter takes
     service objects. Therefore, you can pipe strings and service objects (and objects with properties
     that can be converted to string and service objects) to Start-Service.

     If the parameter binding component of Windows PowerShell cannot associate the piped objects
     with a parameter of the receiving cmdlet, the command fails and Windows PowerShell prompts you
     for the missing parameter values.

     You cannot force the parameter binding component to associate the piped objects with a particular
     parameter -- you cannot even suggest a parameter. Instead, the logic of the component manages
     the piping as efficiently as possible.

ONE-AT-A-TIME PROCESSING

     Piping objects to a command is much like using a parameter of the command to submit the
     objects.

     For example, piping objects representing the services on the computer to a Format-Table command,
     such as:

          get-service | format-table -property name, dependentservices

     is much like saving the service objects in a variable and using the InputObject parameter
     of Format-Table to submit the service object.

          $services = get-service
                  format-table -inputobject $services -property name, dependentservices

     or imbedding the command in the parameter value

                  format-table -inputobject (get-service wmi) -property name, dependentservices

     However, there is an important difference. When you pipe multiple objects to a command,
     Windows PowerShell sends the objects to the command one at a time. When you use a
     command parameter, the objects are sent as a single array object.

     This seemingly technical difference can have interesting, and sometimes useful, consequences.

     For example, if you pipe multiple process objects from the Get-Process cmdlet to the
     Get-Member cmdlet, Windows PowerShell sends each process object, one at a time, to Get-Member.
     Get-Member displays the .NET class (type) of the process objects, and their properties and methods.
     (Get-Member eliminates duplicates, so if the objects are all of the same type, it displays only
     one object type.)

     In this case, Get-Member displays the properties and methods of each process object, that is, a
     System.Diagnostics.Process object.

                 get-process | get-member

                    TypeName: System.Diagnostics.Process

                 Name                           MemberType     Definition
                 ----                           ----------     ----------
                 Handles                        AliasProperty  Handles = Handlecount
                 Name                           AliasProperty  Name = ProcessName
                 NPM                            AliasProperty  NPM = NonpagedSystemMemorySize
                 ...

      However, if you use the InputObject parameter of Get-Member, then Get-Member receives an
      array of System.Diagnostics.Process objects as a single unit, and it displays the properties
      of an array of objects. (Note the array symbol ([]) after the System.Object type name.)

                get-member -inputobject (get-process)

                TypeName: System.Object[]

                Name               MemberType    Definition
                ----               ----------    ----------
                Count              AliasProperty Count = Length
                Address            Method        System.Object& Address(Int32 )
                Clone              Method        System.Object Clone()
                ...

     This result might not be what you intended, but after you understand it, you can use it. For
     example, an array of process objects has a Count property that you can use to count the number
     of processes on the computer.

        (get-process).count

     This distinction can be important, so remember that when you pipe objects to a cmdlet, they
     are delivered one at a time.

ACCEPTS PIPELINE INPUT

    In order to receive objects in a pipeline, the receiving cmdlet must have a parameter
    that accepts pipeline input. You can use a Get-Help command with the Full or Parameter
    parameters to determine which, if any, of a cmdlet's parameters accepts pipeline input.

    In the Get-Help default display, the "Accepts pipeline input" item appears in a table
    of parameter attributes. This table is displayed only when you use the Full or Parameter
    parameters of the Get-Help cmdlet.

    For example, to determine which of the parameters of the Start-Service cmdlet accepts
    pipeline input, type:

        get-help start-service -full

        get-help start-service -parameter *

    For example, the help for the Start-Service cmdlet shows that the Name and InputObject
    parameters accept pipeline input ("true"). All other parameters have a value of "false"
    in the "Accept pipeline input?" row.

        -name <string[]>
           Specifies the service names for the service to be started.
           The parameter name is optional. You can use "-Name" or its alias,
           "-ServiceName", or you can omit the parameter name.

           Required?                    true
           Position?                    1
           Default value
      -->  Accept pipeline input?       true (ByValue, ByPropertyName)
           Accept wildcard characters?  true

        -inputObject <ServiceController[]>
           Specifies ServiceController objects representing the services to be started. Enter
           a variable that contains the objects or type a command or expression that gets the
           objects.

           Required?                    false
           Position?                    named
           Default value
      -->  Accept pipeline input?       true (ByValue)
           Accept wildcard characters?  false

     This means that you can send objects (PsObjects) through the pipeline to the
     Where-Object cmdlet and Windows PowerShell will associate the object with the
     InputObject parameter.

METHODS OF ACCEPTING PIPELINE INPUT

     Cmdlets parameters can accept pipeline input in one of two different ways:

     -- ByValue: Parameters that accept input "by value" can accept piped objects
        that have the same .NET type as their parameter value or objects that can be
        converted to that type.

        For example, the Name parameter of Start-Service accepts pipeline input
        by value. It can accept string objects or objects that can be converted to
        strings.

     -- ByPropertyName: Parameters that accept input "by property name" can accept piped
        objects only when a property of the object has the same name as the parameter.

        For example, the Name parameter of Start-Service can accept objects that have
        a Name property.

        (To list the properties of an object, pipe it to Get-Member.)

     Some parameters can accept objects by value or by property name. These parameters are
     designed to take input from the pipeline easily.

INVESTIGATING PIPELINE ERRORS

     If a command fails because of a pipeline error, you can investigate the failure and
     rewrite the command.

     For example, the following command tries to move a registry entry from one
     registry key to another by using the Get-Item cmdlet to get the destination path and
     then piping the path to the Move-ItemProperty cmdlet.

     Specifically, the command uses the Get-Item cmdlet to get the destination path. It uses
     a pipeline operator to send the result to the Move-ItemProperty cmdlet. The Move-ItemProperty
     command specifies the current path and name of the registry entry to be moved.

          get-item -path hklm:\software\mycompany\sales |
          move-itemproperty -path hklm:\software\mycompany\design -name product

     The command fails and Windows PowerShell displays the following error
     message:

         Move-ItemProperty : The input object cannot be bound to any parameters for the
         command either because the command does not take pipeline input or the input
         and its properties do not match any of the parameters that take pipeline input.
         At line:1 char:23
         + $a | move-itemproperty <<<<  -path hklm:\software\mycompany\design -name product

    To investigate, use the Trace-Command cmdlet to trace the Parameter Binding component of
    Windows PowerShell. The following command traces the Parameter Binding component while the
    command is processing. It uses the -pshost parameter to display the results at the console
    and the -filepath command to send them to the debug.txt file for later reference.

         trace-command -name parameterbinding -expression {get-item -path hklm:\software\mycompany\sales |
             move-itemproperty -path hklm:\software\mycompany\design -name product} -pshost -filepath debug.txt

    The results of the trace are lengthy, but they show the values being bound to the Get-Item cmdlet
    and then the named values being bound to the Move-ItemProperty cmdlet.

       ...
        BIND NAMED cmd line args [Move-ItemProperty]
            BIND arg [hklm:\software\mycompany\design] to parameter [Path]
        ...
            BIND arg [product] to parameter [Name]
        ....
        BIND POSITIONAL cmd line args [Move-ItemProperty]
        ...

    Finally, it shows that the attempt to bind the path to the Destination parameter
    of Move-ItemProperty failed.
        ...
        BIND PIPELINE object to parameters: [Move-ItemProperty]
            PIPELINE object TYPE = [Microsoft.Win32.RegistryKey]
            RESTORING pipeline parameter's original values
            Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
            Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
        ...

     To investigate the failure, use the Get-Help cmdlet to view the attributes of the
     Destination parameter. The following command gets detailed information about the
     Destination parameter.

    get-help move-itemproperty -parameter destination

     The results show that Destination takes pipeline input only "by property name".
     That is, the piped object must have a property named Destination.

        -destination <string>
            Specifies the path to the destination location.

            Required?                    true
            Position?                    2
            Default value
            Accept pipeline input?       true (ByPropertyName)
            Accept wildcard characters?  true

     To see the properties of the object being piped to the Move-ItemProperty cmdlet,
     pipe it to the Get-Member cmdlet. The following command pipes the results of the
     first part of the command to the Get-Member cmdlet.

          get-item -path hklm:\software\mycompany\sales | get-member

     The output shows that the item is a Microsoft.Win32.RegistryKey that does not
     have a Destination property. That explains why the command failed.

     To fix the command, we must specify the destination in the Move-ItemProperty cmdlet. We can
     use a Get-ItemProperty command to get the path, but the name and destination must be specified
     in the Move-ItemProperty part of the command.

         get-item -path hklm:\software\mycompany\design |
             move-itemproperty -dest hklm:\software\mycompany\design -name product

     To verify that the command worked, use a Get-ItemProperty command:

    get-itemproperty hklm:\software\mycompany\sales

     The results show that the Product registry entry was moved to the Sales key.

        PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany\sales
        PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany
        PSChildName  : sales
        PSDrive      : HKLM
        PSProvider   : Microsoft.PowerShell.Core\Registry
        Product      : 18

SEE ALSO
    about_objects
    about_parameters
    about_command_syntax
    about_foreach


about_Preference_Variables

TOPIC
    Preference Variables

SHORT DESCRIPTION
    Variables that customize the behavior of Windows PowerShell

LONG DESCRIPTION
    Windows PowerShell includes a set of variables that enable you to
    customize its behavior. These "preference variables" work like the
    options in GUI-based systems.

    The preference variables affect the Windows PowerShell operating
    environment and all commands run in the environment. In many cases,
    the cmdlets have parameters that you can use to override the preference
    behavior for a specific command.

    The following table lists the preference variables and their default
    values.

    Variable                             Default Value
    --------                             -------------
    $ConfirmPreference                   High
    $DebugPreference                     SilentlyContinue
    $ErrorActionPreference               Continue
    $ErrorView                           NormalView
    $FormatEnumerationLimit              4
    $LogCommandHealthEvent               False (not logged)
    $LogCommandLifecycleEvent            False (not logged)
    $LogEngineHealthEvent                True (logged)
    $LogEngineLifecycleEvent             True (logged)
    $LogProviderLifecycleEvent           True (logged)
    $LogProviderHealthEvent              True (logged)
    $MaximumAliasCount                   4096
    $MaximumDriveCount                   4096
    $MaximumErrorCount                   256
    $MaximumFunctionCount                4096
    $MaximumHistoryCount                 64
    $MaximumVariableCount                4096
    $OFS                                 (Space character (" "))
    $OutputEncoding		         ASCIIEncoding object
    $ProgressPreference                  Continue
    $PSEmailServer                       (None)
    $PSSessionApplicationName            WSMAN
    $PSSessionConfigurationName          http://schemas.microsoft.com/powershell/microsoft.powershell
    $PSSessionOption                     (See below)
    $VerbosePreference                   SilentlyContinue
    $WarningPreference                   Continue
    $WhatIfPreference                    0

    Windows Powershell also includes the following environment variables that
    store user preferences. For more information about the environment variables,
    see about_environment_variables.

    Variable
    --------
    PSModulePath

WORKING WITH PREFERENCE VARIABLES
    This document describes each of the preference variables.

    To display the current value of a specific preference variable, type
    the name of the variable. In response, Windows PowerShell provides the
    value. For example, the following command displays the value of the
    $ConfirmPreference variable.

        PS> $ConfirmPreference
        High

    To change the value of a variable, use an assignment statement. For
    example, the following statement assigns the value "Medium" to the
    $ConfirmPreference variable.

        PS> $ConfirmPreference = "Medium"

    Like all variables, the values that you set are specific to the current
    Windows PowerShell window. To make them effective in all Windows
    PowerShell windows, add them to your Windows PowerShell profile. For
    more information, see about_profiles.

WORKING REMOTELY
   When you run commands on a remote computer, the remote commands are subject
   only to the preferences set in the Windows PowerShell client on the remote
   computer. For example, when you run a remote command, the value of the
   $DebugPreference variable on remote computer determines how Windows
   PowerShell responds to debugging messages.

   For more information about remote commands, see about_remote.

$ConfirmPreference
------------------
    Determines which cmdlet actions automatically request confirmation
    from the user before they are performed.

    When the $ConfirmPreference value (High, Medium, Low, None) is
    greater than or equal to the risk of the cmdlet action (High, Medium,
    Low, None), Windows PowerShell automatically requests confirmation
    from the user before performing the action.

    You can use the Confirm parameter of a cmdlet to override the preference
    for a specific command.

        Valid values:
        None:    No cmdlet actions are automatically confirmed.
                         Users must use the Confirm parameter to request
                         confirmation of specific commands.

        Low:     Cmdlet actions with a low, medium, or high risk are
                         automatically confirmed. To suppress confirmation
                         of a specific command, use -Confirm:$false.

        Medium:  Cmdlet actions with a medium or high risk are
                         automatically confirmed. To enable confirmation of
                         a specific command, use -confirm. To suppress
                         confirmation of a specific command, use
                         -confirm:$false.

        High:    Cmdlet actions with a high risk are automatically
              (default)  confirmed. To enable confirmation of a specific
                         command, use -confirm. To suppress confirmation for a
                         specific command, use -confirm:$false.

    DETAILED EXPLANATION
        When a cmdlet action significantly affects the system, such as by
        deleting data or by using a significant amount of system resources,
        Windows PowerShell can automatically prompt you for confirmation
        before performing the action.

        For example,

        PS> remove-item pref2.txt

            Confirm
            Are you sure you want to perform this action?
            Performing operation "Remove File" on Target "C:\pref2.txt".
            [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

        The estimate of the risk is part of the cmdlet known as its
        "ConfirmImpact". You cannot change it.

        Cmdlet that might pose a risk to the system have a Confirm parameter
        that you can use to request or suppress confirmation for a
        specific command.

    Because most cmdlets use the default risk value of Medium, and the
        default value of $ConfirmPreference is High, automatic confirmation
        rarely occurs. However, you can activate automatic confirmation by
        changing the value of $ConfirmPreference to Medium or Low.

    EXAMPLES
      This example shows the effect of the default value of
      $ConfirmPreference. The High value only confirms high-risk cmdlet
      actions. Since most actions are of medium risk, they are not
      automatically confirmed, although you can use the Confirm
      parameter of the cmdlet to request confirmation of a specific
      command.

          PS> $confirmpreference              #Get the current value of the
          High                                 variable

          PS> remove-item temp1.txt           #Delete a file
          PS>                                 #Deleted without confirmation
          PS> remove-item temp2.txt -confirm  #Use the Confirm parameter

          Confirm
          Are you sure you want to perform this action?
          Performing operation "Remove File" on Target "C:\temp2.txt".
          [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

       This example shows the effect of changing the value of
       $ConfirmPrefernce to Medium. Because most cmdlet actions are
       medium-risk, they are automatically confirmed, and you have to use
       the Confirm parameter with a value of $false to suppress the
       confirmation prompt for a specific command.

          PS> $confirmpreference = "Medium"
                                     #Change the value of $ConfirmPreference
          PS> remove-item temp2.txt
                                     #Deleting a file triggers confirmation
          Confirm
          Are you sure you want to perform this action?
          Performing operation "Remove File" on Target "C:\temp2.txt".
          [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

          PS> remove-item temp3.txt -confirm:$false   #Use Confirm parameter
                                                       to suppress confirmation
          PS>

$DebugPreference
------------------
    Determines how Windows PowerShell responds to debugging messages
        generated by a script, cmdlet or provider, or by a Write-Debug
        command at the command line.

        Some cmdlets display debugging messages, which are typically very
        technical messages designed for programmers and technical support
        professionals. By default, debugging messages are not displayed,
        but you can display debugging messages by changing the value of
        $DebugPreference.

        You can also use the Debug common parameter of a cmdlet to display
        or hide the debugging messages for a specific command. For more
        information, type: "get-help about_commonparameters".

        Valid values:
        Stop:               Displays the debug message and stops
                                executing. Writes an error to the console.

             Inquire:            Displays the debug message and asks you
                                whether you want to continue.

            Continue:           Displays the debug message and continues
                                with execution.

            SilentlyContinue:   No effect. The debug message is not
            (Default)           displayed and execution continues without
                                 interruption.

    EXAMPLES

    The following examples show the effect of changing the values of
    $DebugPreference when a Write-Debug command is entered at the command
    line. The change affects all debugging messages, including those
    generated by cmdlets and scripts. The examples also show the use of the
    Debug common parameter, which displays or hides the debugging messages
    related to a single command.

    This example shows the effect of the default value, "SilentlyContinue."
    The debug message is not displayed and processing continues. The final
    command uses the Debug parameter to override the preference for a single
    command.

        PS> $debugpreference                    # Get the current value of
        SilentlyContinue                          $DebugPreference

        PS> write-debug "Hello, World"
        PS>                                     # The debug message is not
                                                  displayed.

        PS> write-debug "Hello, World" -Debug   # Use the Debug parameter
        DEBUG: Hello, World                     # The debug message is
                                                  is requested.                                                                                                    displayed and confirmation
        Confirm
        Continue with this operation?
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

    This example shows the effect of the "Continue" value. The final command
    uses the Debug parameter with a value of $false to suppress the message
    for a single command.

        PS> $debugpreference = "Continue"   # Change the value to "Continue"

        PS> write-debug "Hello, World"
        DEBUG: Hello, World                 # The debug message is displayed
        PS>                                   and processing continues.

        PS> write-debug "Hello, World" -Debug:$false
                                            # Use the Debug parameter with
                                              false.
        PS>                                 # The debug message is not
                                              displayed.

    This example shows the effect of the "Stop" value. The final command
    uses the Debug parameter with a value of $false to suppress the message
    for a single command.

        PS> $debugpreference = "Stop"       #Change the value to "Stop"
        PS> write-debug "Hello, World"
        DEBUG: Hello, World
        Write-Debug : Command execution stopped because the shell variable "DebugPreference" is
        set to Stop.
        At line:1 char:12
        + write-debug  <<<< "Hello, World"

        PS> write-debug "Hello, World" -Debug:$false
                                            # Use the Debug parameter with
                                              $false
        PS>                                 # The debug message is not
                                              displayed and processing is
                                              not stopped.

    This example shows the effect of the "Inquire" value. The final command
    uses the Debug parameter with a value of $false to suppress the message
    for a single command.

        PS> $debugpreference = "Inquire"
        PS> write-debug "Hello, World"
        DEBUG: Hello, World

        Confirm
        Continue with this operation?
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

        PS> write-debug "Hello, World" -Debug:$false
                                            # Use the Debug parameter with
                                              $false
        PS>                                 # The debug message is not
                                              displayed and processing
                                              continues without interruption.

$ErrorActionPreference
----------------------
    Determines how Windows PowerShell responds to a non-terminating
        error (an error that does not stop the cmdlet processing) at the
        command line or in a script, cmdlet, or provider, such as the
        errors generated by the Write-Error cmdlet.

        You can also use the ErrorAction common parameter of a cmdlet to
        override the preference for a specific command. For more
        information, type: "get-help about_commonparameters".

        Valid values:
        Stop:               Displays the error message and stops
                                executing.

             Inquire:            Displays the error message and asks you
                                whether you want to continue.

            Continue:           Displays the error message and continues
                                executing.

            SilentlyContinue:   No effect. The error message is not
            (Default)           displayed and execution continues without
                                interruption.

       Neither $ErrorActionPreference nor the ErrorAction common parameter
       affect how Windows PowerShell responds to terminating errors (those
       that stop cmdlet processing).

       For more information about the ErrorAction common parameter, type
       "get-help about_commonparameters".

    EXAMPLES

    These examples show the effect of the different values of
    $ErrorActionPreference and the use of the ErrorAction common parameter
    to override the preference for a single command. The ErrorAction
    parameter has the same valid values as the $ErrorActionPreference
    variable.

    This example shows the effect of the Continue value, which is the
    default.

        PS> $erroractionpreference
        Continue		# Display the value of the preference.

        PS> write-error "Hello, World"
                                # Generate a non-terminating error.

        write-error "Hello, World" : Hello, World
                                # The error message is displayed and
                                  execution continues.

        PS> write-error "Hello, World" -ErrorAction:SilentlyContinue
                                # Use the ErrorAction parameter with a
                                  value of "SilentlyContinue".
        PS>
                                # The error message is not displayed and
                                  execution continues.

    This example shows the effect of the SilentlyContinue value.

        PS> $ErrorActionPreference = "SilentlyContinue"
                                # Change the value of the preference.
        PS> write-error "Hello, World"
                                # Generate an error message.
        PS>
                                # Error message is suppressed.
        PS> write-error "Hello, World" -erroraction:continue
                                # Use the ErrorAction parameter with a
                                  value of "Continue".
        write-error "Hello, World" -erroraction:continue : Hello, World
                                # The error message is displayed and
                                  execution continues.

    This example shows the effect of a real error. In this case, the command
    gets a non-existent file, nofile.txt. The example also uses the
    ErrorAction common parameter to override the preference.

        PS> $erroractionpreference
        SilentlyContinue        # Display the value of the preference.

        PS> get-childitem -path nofile.txt
        PS>                     # Error message is suppressed.

        PS> $ErrorActionPreference = "Continue"
                                # Change the value to Continue.

        PS> get-childitem -path nofile.txt
        Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
        At line:1 char:4
        + get-childitem  <<<< nofile.txt

        PS> get-childitem -path nofile.txt -erroraction SilentlyContinue
                                # Use the ErrorAction parameter
        PS>
                                # Error message is suppressed.

        PS> $ErrorActionPreference = "Inquire"
                                # Change the value to Inquire.
        PS> get-childitem -path nofile.txt

        Confirm
        Cannot find path 'C:\nofile.txt' because it does not exist.
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): y

        Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
        At line:1 char:4
        + get-childitem  <<<< nofile.txt

        PS> $ErrorActionPreference = "Continue"
                                # Change the value to Continue.
        PS> Get-Childitem nofile.txt -erroraction "Inquire"
                                # Use the ErrorAction parameter to override
                                  the preference value.

        Confirm
        Cannot find path 'C:\nofile.txt' because it does not exist.
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

$ErrorView
----------
        Determines the display format of error messages in Windows
        PowerShell.

        Valid values:
        NormalView:         A detailed view designed for most users.
            (default)           Consists of a description of the error, the
                                name of the object involved in the error,
                                and arrows (<<<<) that point to the words
                                in the command that caused the error.

             CategoryView:       A succinct, structured view designed for
                                production environments. The format is:
                                {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}

        For more information about the fields in CategoryView, see
        "ErrorCategoryInfo class" in the Windows PowerShell SDK.

    EXAMPLES

    These example show the effect of the ErrorView values.

    This example shows how an error appears when the value of $ErrorView is
    NormalView. In this case, the Get-ChildItem command is used to find a
    non-existent file.

        PS> $ErrorView                         # Verify the value.
        NormalView

        PS> get-childitem nofile.txt           # Find a non-existent file.
        Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
        At line:1 char:14
        + get-childitem  <<<< nofile.txt

    This example shows how the same error appears when the value of
    $ErrorView is CategoryView.

        PS> $ErrorView = "CategoryView"        # Change the value to
                                                 CategoryView

        PS> get-childitem nofile.txt
        ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException

   This example demonstrates that the value of ErrorView only affects the
   error display; it does not change the structure of the error object that
   is stored in the $error automatic variable. For information about the $error
   automatic variable, see about_automatic_variables.

   This command takes the ErrorRecord object associated with the most recent
   error in the error array (element 0) and formats all of the properties
   of the error object in a list.

        PS> $error[0] | format-list -property * -force

        Exception    : System.Management.Automation.ItemNotFoundException: Cannot find path
                       'C:\nofile.txt' because it does not exist.
                       at System.Management.Automation.SessionStateInternal.GetChildItems(String path,
                       Boolean recurse, CmdletProviderContext context)
                       at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(String path,
                       Boolean recurse, CmdletProviderContext context)
                       at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord()
        TargetObject          : C:\nofile.txt
        CategoryInfo          : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem],
                                ItemNotFoundException
        FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
        ErrorDetails          :
        InvocationInfo        : System.Management.Automation.InvocationInfo

$FormatEnumerationLimit
-----------------------
        Determines how many enumerated items are included in a display. This
        variable does not affect the underlying objects; just the display.
        When the value of $FormatEnumerationLimit is less than the number of
        enumerated items, Windows PowerShell adds an ellipsis (...) to
        indicate items not shown.

        Valid values: Integers (Int32)
        Default value: 4

    EXAMPLES

        This example shows how to use the $FormatEnumerationLimit variable
        to improve the display of enumerated items.

        The command in this example generates a table that lists all of the
        services running on the computer in two groups; one for running
        services and one for stopped services. It uses a Get-Service
        command to get all of the services, and then send the results
        through the pipeline to the Group-Object cmdlet, which groups the
        results by the service status.

        The resulting display is a table that lists the status in the Name
        column and the processes with that status in the Group column. (To
        change the column labels, use a hash table. For more information,
        see the examples in "get-help format-table -examples".)

        There are a maximum of 4 services listed in the Group column for
        each status. To increase the number of items listed, increase
        the value of $FormatEnumerationLimit to 1000.

        In the resulting display, the list in the Group column is now
        limited by the line length. In the final command in the example, use
        the Wrap parameter of Format-Table to display all of the processes
        in each Status group.

        PS> $formatenumerationlimit         # Find the current value
        4

        PS> get-service | group-object -property status
                                            # List all services grouped by
                                              status

        Count Name                      Group
        ----- ----                      -----
           60 Running                   {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...}
           41 Stopped                   {Alerter, AppMgmt, aspnet_state, ATI Smart...}

                                           # The list is truncated after
                                             4 items.

        PS> $formatenumerationlimit = 1000
                                           # Increase the limit to 1000.

        PS> get-service | group-object -property status
                                           # Repeat the command.

        Count Name     Group
        ----- ----     -----
           60 Running  {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec...
           41 Stopped  {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc...

        PS> get-service | group-object -property status | format-table -wrap
                                           # Add the Wrap parameter.

        Count Name       Group
        ----- ----       -----
           60 Running    {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, Client
                         for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, Dnscache, ERSvc,
                         Eventlog, EventSystem, FwcAgent, helpsvc, HidServ, IISADMIN,
                         InoRPC, InoRT, InoTask, lanmanserver, lanmanworkstation, LmHosts,
                         MDM, Netlogon, Netman, Nla, NtLmSsp, PlugPlay, PolicyAgent,
                         ProtectedStorage, RasMan, RemoteRegistry, RpcSs, SamSs, Schedule,
                         seclogon, SENS, SharedAccess, ShellHWDetection, SMT PSVC, Spooler,
                         srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, TrkWks,
                         UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, wuauserv,
                         WZCSVC, zzInterix}

           41 Stopped    {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc,
                         ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, CronService,
                         dmadmin, FastUserSwitchingCompatibility, HTTPFilter, ImapiService,
                         Mapsvc, Messenger, mnmsrvc, MSDTC, MSIServer, msvsmon80, NetDDE,
                         NetDDEdsdm, NtmsSvc, NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess,
                         RpcLocator, RSVP, SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost,
                         UPS, VSS, WmdmPmSN, Wmi, WmiApSrv, xmlprov}

$Log*Event
----------
        The Log*Event preference variables determine which types of events
        are written to the Windows PowerShell event log in Event Viewer. By
        default, only engine and provider events are logged, but you can use
        the Log*Event preference variables to customize your log, such as
        logging events about commands.

        The Log*Event preference variables are as follows:

            $LogCommandHealthEvent: Logs errors and exceptions in command initialization
                and processing. Default = $false (not logged).

            $LogCommandLifecycleEvent:
                Logs the starting and stopping of commands and command pipelines
                and security exceptions in command discovery. Default = $false (not logged).

            $LogEngineHealthEvent: Logs errors and failures of sessions. Default = $true (logged).

            $LogEngineLifecycleEvent: Logs the opening and closing of sessions.
                Default = $true (logged).

            $LogProviderHealthEvent: Logs provider errors, such as read and write errors,
                lookup errors, and invocation errors. Default = $true (logged).

            $LogProviderLifecycleEvent: Logs adding and removing of Windows PowerShell providers.
                Default = $true (logged). (For information about Windows PowerShell providers, type:
                "get-help about_provider".

        To enable a Log*Event, type the variable with a value of $true, for example:

            $LogCommandLifeCycleEvent

            - or -

            $LogCommandLifeCycleEvent = $true

        To disable an event type, type the variable with a value of $false, for example:

            $LogCommandLifeCycleEvent = $false

        The events that you enable are effective only for the current Windows PowerShell
        console. To apply the configuration to all consoles, save the variable settings
        in your Windows PowerShell profile.

$MaximumAliasCount
------------------
        Determines how many aliases are permitted in a Windows PowerShell
        session. The default value, 4096, should be sufficient for most
        uses, but you can adjust it to meet your needs.

        Valid values: 1024 - 32768 (Int32)
        Default: 4096

        To count the aliases on your system, type:

        (get-alias).count

$MaximumDriveCount
------------------
        Determines how many Windows PowerShell drives are permitted in a
        given session. This includes file system drives and data stores that
        are exposed by Windows PowerShell providers and appear as drives,
        such as the Alias: and HKLM: drives.

        Valid values: 1024 - 32768 (Int32)
        Default: 4096

        To count the aliases on your system, type:

        (get-psdrive).count

$MaximumErrorCount
------------------
        Determines how many errors are saved in the error history
        for the session.

        Valid values: 256 - 32768 (Int32)
        Default: 256

        Objects that represent each retained error are stored in the
        $Error automatic variable. This variable contains an array of error
        record objects, one for each error. The most recent error is the
        first object in the array ($Error[0]).

        To count the errors on your system, use the Count property of
        the $Error array. Type:

        $Error.count

        To display a specific error, use array notation to display
        the error. For example, to see the most recent error, type:

                $Error[0]

        To display the oldest retained error, type:

                $Error[($Error.Count -1]

        To display the properties of the ErrorRecord object, type:

                $Error[0] | format-list -property * -force

        In this command, the Force parameter overrides the special
        formatting of ErrorRecord objects and reverts to the conventional
        format.

        To delete all errors from the error history, use the Clear method
        of the error array.

               PS> $Error.count
               17
               PS> $Error.clear()
               PS>
               PS> $Error.count
               0

       To find all properties and methods of an error array, use the
       Get-Member cmdlet with its InputObject parameter. When you pipe a
       collection of objects to Get-Member, Get-Member displays the
       properties and methods of the objects in the collection. When you use
       the InputObject parameter of Get-Member, Get-Member displays the
       properties and methods of the collection.

$MaximumFunctionCount
------------------
        Determines how many functions are permitted in a given session.

        Valid values: 1024 - 32768 (Int32)
        Default: 4096

        To see the functions in your session, use the Windows PowerShell
        Function: drive that is exposed by the Windows PowerShell Function
        provider. (For more information about the Function provider, type
        "get-help function").

        To list the functions in the current session, type:

            get-childitem function:

        To count the functions in the current session, type:

            (get-childitem function:).count

$MaximumHistoryCount
------------------
        Determines how many commands are saved in the command history
        for the current session.

        Valid values: 1 - 32768 (Int32)
        Default: 64

        To determine the number of commands current saved in the command
        history, type:

            (get-history).count

        To see the command saved in your session history, use the
        Get-History cmdlet. For more information, type:
        "get-help about_history".

$MaximumVariableCount
------------------
        Determines how many variables are permitted in a given session,
        including automatic variables, preference variables, and the
        variables that you create in commands and scripts.

        Valid values: 1024 - 32768 (Int32)
        Default: 4096

        To see the variables in your session, use the Get-Variable cmdlet
        and the features of the Windows PowerShell Variable: drive and the
        Windows PowerShell Variable provider. For information about the
        Variable provider, type "get-help variable".

        To find the current number of variables on the system, type:

            (get-variable).count

$OFS
----
        Output Field Separator. Specifies the character that separates the
        elements of an array when the array is converted to a string.

        Valid values: Any string.
        Default: Space

        By default, the $OFS variable does not exist and the output file
        separator is a space, but you can add this variable and set it to
        any string.

    EXAMPLES

    This example shows that a space is used to separate the values when an
    array is converted to a string. In this case, an array of integers is
    stored in a variable and then the variable is cast as a string.

       PS> $array = 1,2,3                 # Store an array of integers.

       PS> [string]$array                 # Cast the array to a string.
       1 2 3                              # Spaces separate the elements

    To change the separator, add the $OFS variable by assigning a value
    to it. To work correctly, the variable must be named $OFS.

       PS> $OFS = "+"                     # Create $OFS and assign a "+"

       PS> [string]$array                 # Repeat the command
       1+2+3                              # Plus signs separate the elements

    To restore the default behavior, you can assign a space (" ") to
    the value of $OFS or delete the variable. This command deletes the
    variable and then verifies that the separator is a space.

       PS> Remove-Variable OFS            # Delete $OFS
       PS>

       PS> [string]$array                 # Repeat the command
       1 2 3                              # Spaces separate the elements

$OutputEncoding
---------------
       Determines the character encoding method used by Windows PowerShell
       when it sends text to other applications. For example, if an
       application returns Unicode strings to Windows PowerShell, you might
       need to change the value to to send the characters correctly.

        Valid values: Objects derived from an encoding class, such as
                      ASCIIEncoding, SBCSCodePageEncoding, UTF7Encoding,
                      UTF8Encoding, UTF32Encoding, and UnicodeEncoding.

        Default: ASCIIEncoding object (System.Text.ASCIIEncoding)

    EXAMPLES

       This example shows how to make the FINDSTR command in Windows
       work in Windows PowerShell on a computer that is localized for
       a language that uses Unicode characters, such as Chinese.

       The first command finds the value of $OutputEncoding. Because the
       value is an encoding object, display only its EncodingName property.

          PS> $OutputEncoding.EncodingName  # Find the current value
          US-ASCII

       In this example, a FINDSTR command is used to search for two Chinese
       characters that are present in the Test.txt file. When this FINDSTR
       command is run in the Windows Command Prompt (Cmd.exe), FINDSTR finds
       the characters in the text file. However, when you run the same
       FINDSTR command in Windows PowerShell, the characters are not found
       because the Windows PowerShell sends them to FINDSTR in ASCII text,
       instead of in Unicode text.

          PS> findstr <Unicode-characters>  # Use findstr to search.
          PS>                               # None found.

       To make the command work in Windows PowerShell, set the value of
       $OutputEncoding to the value of the OutputEncoding property of the
       console, which is based on the locale selected for Windows. Because
       OutputEncoding is a static property of the console, use
       double-colons (::) in the command.

          PS> $OutputEncoding = [console]::outputencoding
          PS>                               # Set the value equal to the
                                              OutputEncoding property of the
                                              console.
          PS> $OutputEncoding.EncodingName
          OEM United States
                                            # Find the resulting value.

       As a result of this change, the FINDSTR command finds the characters.

          PS> findstr <Unicode-characters>
          test.txt:         <Unicode-characters>

                    # Use findstr to search. It find the
                                          characters in the text file.

$ProgressPreference
-------------------
    Determines how Windows PowerShell responds to progress updates
        generated by a script, cmdlet or provider, such as the progress bars
        generated by the Write-Progress cmdlet. The Write-Progress cmdlet
        creates progress bars that depict the status of a command.

        Valid values:
        Stop:               Does not display the progress bar. Instead,
                                it displays an error message and stops executing.

             Inquire:            Does not display the progress bar. Prompts
                                for permission to continue. If you reply
                                with Y or A, it displays the progress bar.

            Continue:           Displays the progress bar and continues with
            (Default)           execution.

            SilentlyContinue:   Executes the command, but does not display
                                the progress bar.

$PSEmailServer
--------------
       Specifies the default e-mail server that is used to send e-mail
       messages. This preference variable is used by cmdlets that send
       e-mail, such as the Send-MailMessage cmdlet.

$PSSessionApplicationName
---------------------------
       Specifies the default application name for a remote command
       that uses WS-Management technology.

       The system default application name is WSMAN, but you can use this
       preference variable to change the default.

       The application name is the last node in a connection URI. For
       example, the application name in the following sample URI is
       WSMAN.

           http://Server01:8080/WSMAN

       The default application name is used when the remote command
       does not specify a connection URI or an application name.

       The WinRM service uses the application name to select a listener
       to service the connection request. The value of this parameter
       should match the value of the URLPrefix property of a listener
       on the remote computer.

       To override the system default and the value of this variable,
       and select a different application name for a particular session,
       use the ConnectionURI or ApplicationName parameters of the
       New-PSSession, Enter-PSSession or Invoke-Command cmdlets.

       This preference variable is set on the local computer, but it
       specifies a listener on the remote computer. If the application
       name that you specify does not exist on the remote computer,
       the command to establish the session fails.

$PSSessionConfigurationName
---------------------------
       Specifies the default session configuration that is used for
       PSSessions created in the current session.

       This preference variable is set on the local computer, but it
       specifies a session configuration that is located on the remote
       computer.

       The value of the $PSSessionConfigurationName variable is a fully
       qualified resource URI.

       The default value:

         http://schemas.microsoft.com/powershell/microsoft.powershell

       indicates the Microsoft.PowerShell session configuration
       on the remote computer.

       If you specify only a configuration name, the following schema URI
       is prepended:

           http://schemas.microsoft.com/powershell/

       You can override the default and select a different session
       configuration for a particular session by using the
       ConfigurationName parameter of the New-PSSession, Enter-PSSession
       or Invoke-Command cmdlets.

       You can change the value of this variable at any time. When you
       do, remember that the session configuration that you select must
       exist on the remote computer. If it does not, the command to
       create a session that uses the session configuration fails.

       This preference variable does not determine which local session
       configurations are used when remote users create a session that
       connects to this computer. However, you can use the permissions
       for the local session configurations to determine which users
       may use them.

$PSSessionOption
----------------
        Establishes the default values for advanced user options in a
        remote session. These option preferences override the system
        default values for session options.

        You can also set custom options for a particular remote session by
        using the SessionOption parameter in cmdlets that create a session,
        such as New-PSSession, Enter-PSSession, and Invoke-Command. The
        SessionOption parameter value takes precedence over the system defaults
        and the defaults that are set in this variable.

        The $PSSessionOption variable contains a PSSessionOption object
        (System.Management.Automation.Remoting.PSSessionObject). Each
        property of the object represents a session option. For example,
        the NoCompression property turns of data compression during the
        session.

        To create the $PSSessionOption preference variable, use the
        New-PSSessionOption cmdlet. Save the output in a variable called
        $PSSessionOption.

        For example,

            $PSSessionOption = New-PSSessionOption -NoCompression

        To use the $PSSessionOption preference variable in every
        Windows PowerShell session, add a New-PSSessionOption command
        that creates the $PSSessionOption variable to your Windows
        PowerShell profile.

        For more information about the New-PSSessionOption cmdlet, see
        the help topic for New-PSSessionOption. For more information about
        remote commands and sessions, see about_Remote and about_PSSessions.
        For more information about using a profile, see about_Profiles.

$VerbosePreference
------------------
           Determines how Windows PowerShell responds to verbose messages
        generated by a script, cmdlet or provider, such as the messages
        generated by the Write-Verbose cmdlet. Typically, verbose messages
        describe the actions performed to execute a command.

        By default, verbose messages are not displayed, but you can change
        this behavior by changing the value of $VerbosePreference.

        You can also use the Verbose common parameter of a cmdlet to display
        or hide the verbose messages for a specific command. For more
        information, type: "get-help about_commonparameters".

        Valid values:
        Stop:               Displays the verbose message and an error
                                message and then stops executing.

             Inquire:            Displays the verbose message and then
                                displays a prompt that asks you whether you
                                want to continue.

            Continue:           Displays the verbose message and then continues with execution.

            SilentlyContinue:   Does not display the verbose message. Continues executing.
            (Default)

    EXAMPLES

    These examples show the effect of the different values of $VerbosePreference and the use of the
    Verbose common parameter to override the preference value.

    This example shows the effect of the SilentlyContinue value, which is the default.

        PS> $VerbosePreference             # Find the current value.
        SilentlyContinue

        PS> Write-Verbose "Verbose message test."
        PS>                                # Write a verbose message.
                                           # Message is not displayed.

        PS> Write-Verbose "Verbose message test." -verbose
        VERBOSE: Verbose message test.
                                       # Use the Verbose parameter.

    This example shows the effect of the Continue value.

        PS> $VerbosePreference = "Continue"
                                           # Change the value to Continue.
        PS> Write-Verbose "Verbose message test."
                                           # Write a verbose message.
        VERBOSE: Verbose message test.
                                           # Message is displayed.

        PS> Write-Verbose "Verbose message test." -verbose:$false
                                           # Use the Verbose parameter with
                                             a value of $false.
        PS>
                                           # Message is not displayed.

    This example shows the effect of the Stop value.

        PS> $VerbosePreference = "Stop"
                                           # Change the value to Stop.
        PS> Write-Verbose "Verbose message test."
                                           # Write a verbose message.
        VERBOSE: Verbose message test.
        Write-Verbose : Command execution stopped because the shell variable "VerbosePreference"
        is set to Stop.
        At line:1 char:14
        + Write-Verbose  <<<< "Verbose message test."

       PS> Write-Verbose "Verbose message test." -verbose:$false
                                          # Use the Verbose parameter with
                                            a value of $false
       PS>
                                          # Message is not displayed.

    This example shows the effect of the Inquire value.

       PS> $VerbosePreference = "Inquire"
                                         # Change the value to Inquire.
       PS> Write-Verbose "Verbose message test."
       VERBOSE: Verbose message test.
                                         # Write a verbose message.
       Confirm
       Continue with this operation?
       [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): y
       PS>

       PS> Write-Verbose "Verbose message test." -verbose:$false
                                        # Use the Verbose parameter.
       PS>
                                        # Message is not displayed.

$WarningPreference
------------------
        Determines how Windows PowerShell responds to warning messages
        generated by a script, cmdlet or provider, such as the messages
        generated by the Write-Warning cmdlet.

        By default, warning messages are displayed and execution continues,
        but you can change this behavior by changing the value of
        $WarningPreference.

        You can also use the WarningAction common parameter of a cmdlet to
        determine how Windows PowerShell responds to warnings from a particular
        command. For more information, type: "get-help about_commonparameters".

        Valid values:
        Stop:               Displays the warning message and an error
                                message and then stops executing.

             Inquire:            Displays the warning message and then
                                prompts for permission to continue.

            Continue:           Displays the warning message and then
            (Default)           continues executing.

            SilentlyContinue:   Does not display the warning message.
                                Continues executing.

    EXAMPLES

    These examples show the effect of the different values of
    $WarningPreference and the use of the WarningAction common parameter
    to override the preference value.

    This example shows the effect of the Continue value, which is the
    default.

            PS> $WarningPreference    # Find the current value.
            Continue

                                      # Write a warning message.
            PS> Write-Warning "This action can delete data."
            WARNING: This action can delete data.

                                      # Use the WarningAction parameter to
                                      # suppress the warning for this command
            PS> Write-Warning "This action can delete data." -warningaction silentlycontinue

   This example shows the effect of the SilentlyContinue value.

            PS> $WarningPreference = "SilentlyContinue"
                                      # Change the value to SilentlyContinue.

            PS> Write-Warning "This action can delete data."
            PS>                        # Write a warning message.

            PS> Write-Warning "This action can delete data." -warningaction stop
                                      # Use the WarningAction parameter to stop
                                      # processing when this command generates a
                                      # warning.
            WARNING: This action can delete data.
            Write-Warning : Command execution stopped because the shell variable
            "WarningPreference" is set to Stop.
            At line:1 char:14
            + Write-Warning <<<<  "This action can delete data." -warningaction stop

    This example shows the effect of the Inquire value.

           PS> $WarningPreference = "Inquire"
                                      # Change the value to Inquire.
           PS> Write-Warning "This action can delete data."
                                      # Write a warning message.
           WARNING: This action can delete data.

           Confirm
           Continue with this operation?
           [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): y
           PS>

           PS> Write-Warning "This action can delete data." -warningaction silentlycontinue
           PS>                         # Use the WarningAction parameter to change the
                                       # response to a warning for the current command.

     This example shows the effect of the Stop value.

           PS> $WarningPreference = "Stop"
                                     # Change the value to Stop.

           PS> Write-Warning "This action can delete data."
                                     # Write a warning message.
           WARNING: This action can delete data.
           Write-Warning : Command execution stopped because the shell variable
             "WarningPreference" is set to Stop.
           At line:1 char:14
           + Write-Warning  <<<< "This action can delete data."

           PS> Write-Warning "This action can delete data." -warningaction inquire
           WARNING: This action can delete data.

           Confirm
           Continue with this operation?
           [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):
                                       # Use the WarningAction parameter to change the
                                       # response to a warning for the current command.

$WhatIfPreference
------------------
           Determines whether WhatIf is automatically enabled for every command
        that supports it. When WhatIf is enabled, the cmdlet reports the
        expected effect of the command, but does not execute the command.

        Valid values:
        0:                  WhatIf is not automatically enabled. To
            (Default)           enable it manually, use the WhatIf parameter
                                of the command.

             1:                  WhatIf is automatically enabled on any
                                command that supports it. Users can use the
                                WhatIf command with a value of False to
                                disable it manually (WhatIf:$false).

    DETAILED EXPLANATION

        When a cmdlet supports WhatIf, the cmdlet reports the expected
        effect of the command, instead of executing the command. For
        example, instead of deleting the test.txt file in response to a
        Remove-Item command, Windows PowerShell reports what it would
        delete. A subsequent Get-Childitem command confirms that the file
        was not deleted.

              PS> remove-item test.txt
              What if: Performing operation "Remove-Item" on Target "Item:
                C:\test.txt
              PS> get-childitem test.txt

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

              Mode                LastWriteTime     Length     Name
              ----                -------------     ------     ----
              -a---         7/29/2006   7:15 PM         84     test.txt

    EXAMPLES

    These examples show the effect of the different values of
    $WhatIfPreference. They also show how to use the WhatIf cmdlet parameter
    to override the preference value for a specific command.

    This example shows the effect of the 0 (not enabled) value, which is the
    default.

             PS> $whatifpreference
             0                         # Check the current value.

             PS> get-childitem test.txt | format-list FullName
             FullName : C:\test.txt
                                       # Verify that the file exists.

             PS> remove-item test.txt
             PS>                       # Delete the file.

             PS> get-childitem test.txt | format-list -property FullName
                                       # Verify that the file is deleted.

             Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist.
             At line:1 char:14
             + get-childitem  <<<< test.txt | format-list fullname

     This example shows the effect of using the WhatIf parameter when the
     value of $WhatIfPreference is 0.

             PS> get-childitem test2.txt | format-list -property FullName
             FullName : C:\test2.txt
                                      # Verify that the file exists.

             PS> remove-item test2.txt -whatif
             What if: Performing operation "Remove File" on Target "C:\test2.txt".
                                      # Use the WhatIf parameter

             PS> get-childitem test2.txt | format-list -property FullName
             FullName : C:\test2.txt
                                      # Verify that the file was not deleted

    This example shows the effect of the 1 (WhatIf enabled) value. When you
    use Remove-Item to delete a cmdlet, Remove-Item displays the path to the
    file that it would delete, but it does not delete the file.

             PS> $whatifpreference = 1
             PS> $whatifpreference
             1                        # Change the value.

             PS> remove-item test.txt
             What if: Performing operation "Remove File" on Target "C:\test.txt".
                                      # Try to delete a file.

             PS> get-childitem test.txt | format-list FullName
             FullName : C:\test.txt
                                      # Verify that the file exists.

     This example shows how to delete a file when the value of
     $WhatIfPreference is 1. It uses the WhatIf parameter with a value of
     $false.

             PS> remove-item test.txt -whatif:$false
                                      # Use the WhatIf parameter with $false.

     This example demonstrates that some cmdlets support WhatIf behavior and
     others do not. In this example, in which the value of $WhatIfPreference
     is 1 (enabled), a Get-Process command, which does not support WhatIf,
     is executed, but a Stop-Process command performs the WhatIf behavior.
     You can override the WhatIf behavior of the Stop-Process command by
     using the WhatIf parameter with a value of $false.

            PS> $whatifpreference = 1
                                     # Change the value to 1.

            PS> get-process winword
                                    # A Get-Process command completes.

            Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
            -------  ------    -----      ----- -----   ------     -- -----------
                234       8     6324      15060   154     0.36   2312 WINWORD

           PS> stop-process -name winword
           What if: Performing operation "Stop-Process" on Target "WINWORD (2312)".
                                    # A Stop-Process command uses WhatIf.

           PS> stop-process -name winword  -whatif:$false
           PS>                      # WhatIf:$false overrides the preference.

           PS> get-process winword
           Get-Process : Cannot find a process with the name 'winword'. Verify the process name
            and call the cmdlet again.
           At line:1 char:12
           + get-process  <<<< winword
                                    # Verify that the process is stopped.

SEE ALSO
    about_Automatic_Variables
    about_CommonParameters
    about_Environment_Variables
    about_Profiles
    about_Remote
    about_Scopes
    about_Variables


about_Profiles

TOPIC
    about_Profiles

SHORT DESCRIPTION
    Describes how to create and use a Windows PowerShell profile.

LONG DESCRIPTION
    You can create a Windows PowerShell profile to customize your environment
    and to add session-specific elements to every Windows PowerShell session
    that you start.

    A Windows PowerShell profile is a script that runs when Windows PowerShell
    starts. You can use the profile as a logon script to customize the
    environment. You can add commands, aliases, functions, variables, snap-ins,
    modules, and Windows PowerShell drives. You can also add other
    session-specific elements to your profile so they are available in every
    session without having to import or re-create them.

    Windows PowerShell supports several profiles for users and host programs.
    However, it does not create the profiles for you. This topic describes the
    profiles, and it describes how to create and maintain profiles on your
    computer.

    It explains how to use the NoProfile parameter of the Windows PowerShell
    console (PowerShell.exe) to start Windows PowerShell without any profiles.
    And, it explains the effect of the Windows PowerShell execution policy on
    profiles.

 THE PROFILE FILES

    Windows PowerShell supports several profile files. Also, Windows PowerShell
    host programs can support their own host-specific profiles.

    For example, the Windows PowerShell console supports the following basic
    profile files. The profiles are listed in precedence order. The first
    profile has the highest precedence.

        Description                Path
        -----------                ----
        Current User, Current Host $Home\[My ]Documents\WindowsPowerShell\Profile.ps1
        Current User, All Hosts    $Home\[My ]Documents\Profile.ps1
        All Users, Current Host    $PsHome\Microsoft.PowerShell_profile.ps1
        All Users, All Hosts       $PsHome\Profile.ps1

    The profile paths include the following variables:

        - The $PsHome variable, which stores the installation directory for
          Windows PowerShell.

        - The $Home variable, which stores the current user's home directory.

    In addition, other programs that host Windows PowerShell can support their
    own profiles. For example, Windows PowerShell Integrated Scripting
    Environment (ISE) supports the following host-specific profiles.

        Description                Path
        -----------                -----
        Current user, Current Host $Home\[My ]Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
        All users, Current Host    $PsHome\Microsoft.PowerShellISE_profile.ps1

    In Windows PowerShell Help, the "CurrentUser, Current Host" profile is the profile most
    often referred to as "your Windows PowerShell profile".

 THE $PROFILE VARIABLE

    The $Profile automatic variable stores the paths to the Windows PowerShell
    profiles that are available in the current session.

    To view a profile path, display the value of the $Profile variable. You can
    also use the $Profile variable in a command to represent a path.

    The $Profile variable stores the path to the "Current User,
    Current Host" profile. The other profiles are saved in note properties of
    the $profile variable.

    For example, the $Profile variable has the following values in the Windows
    PowerShell console.

        Name                               Description
        -----------                        -----------
        $Profile                           Current User,Current Host
        $Profile.CurrentUserCurrentHost    Current User,Current Host
        $Profile.CurrentUserAllHosts       Current User,All Hosts
        $Profile.AllUsersCurrentHost       All Users, Current Host
        $Profile.AllUsersAllHosts          All Users, All Hosts

    Because the values of the $Profile variable change for each user and in
    each host application, ensure that you display the values of the
    profile variables in each Windows PowerShell host application that you use.

    To see the current values of the $Profile variable, type:

        $profile | get-member -type noteproperty

    You can use the $Profile variable in many commands. For example, the
    following command opens the "Current User, Current Host" profile in
    Notepad:

    notepad $profile

    The following command determines whether an "All Users, All Hosts" profile
    has been created on the local computer:

    test-path $profile.AllUsersAllHosts

 HOW TO CREATE A PROFILE

    To create a Windows PowerShell profile, use the following command format:

        if (!(test-path <profile-name>))
           {new-item -type file -path <profile-name> -force}

    For example, to create a profile for the current user in the current
    Windows PowerShell host application, use the following command:

        if (!(test-path $profile))
           {new-item -type file -path $profile -force}

    In this command, the If statement prevents you from overwriting an existing
    profile. Replace the value of the <profile-path> placeholder with the path
    to the profile file that you want to create.

    Note: To create "All Users" profiles in Windows Vista and later versions
          of Windows, start Windows PowerShell with the "Run as administrator"
          option.

 HOW TO EDIT A PROFILE

    You can open any Windows PowerShell profile in a text editor, such as
    Notepad.

    To open the profile of the current user in the current Windows PowerShell
    host application in Notepad, type:

        notepad $profile

    To open other profiles, specify the profile name. For example, to open the
    profile for all the users of all the host applications, type:

        notepad $profile.AllUsersAllHosts

    To apply the changes, save the profile file, and then restart Windows
    PowerShell.

 HOW TO CHOOSE A PROFILE

    If you use multiple host applications, put the items that you use in all
    the host applications into your $Profile.CurrentUserAllHosts profile.
    Put items that are specific to a host application, such as a command that
    sets the background color for a host application, in a profile that is
    specific to that host application.

    If you are an administrator who is customizing Windows
    PowerShell for many users, follow these guidelines:

        -- Store the common items in the $profile.AllUsersAllHosts profile.

        -- Store items that are specific to a host application in
           $profile.AllUsersCurrentHost profiles that are specific to the host
           application.

        -- Store items for particular users in the user-specific profiles.

    Be sure to check the host application documentation for any special
    implementation of Windows PowerShell profiles.

 HOW TO USE A PROFILE

    Many of the items that you create in Windows PowerShell and most commands
    that you run affect only the current session. When you end the session,
    the items are deleted.

    The session-specific commands and items include variables, preference
    variables, aliases, functions, commands (except for Set-ExecutionPolicy),
    and Windows PowerShell snap-ins that you add to the session.

    To save these items and make them available in all future sessions, add
    them to a Windows PowerShell profile.

    Another common use for profiles is to save frequently-used functions,
    aliases, and variables. When you save the items in a profile, you can
    use them in any applicable session without re-creating them.

 HOW TO START A PROFILE

    When you open the profile file, it is blank. However, you can fill it with
    the variables, aliases, and commands that you use frequently.

    Here are a few suggestions to get you started.

    -- Add commands that make it easy to open your profile. This is especially
       useful if you use a profile other than the "Current User, Current Host"
       profile. For example, add the following command:

           function pro {notepad $profile.CurrentUserAllHosts}

    -- Add a function that opens Windows PowerShell Help in a compiled HTML
       Help file (.chm).

           function Get-CHM
            {
               (invoke-item $env:windir\help\mui\0409\WindowsPowerShellHelp.chm)
            }

       This function opens the English version of the .chm file. However, you
       can replace the language code (0409) to open other versions of the .chm
       file.

    -- Add a function that lists the aliases for any cmdlet.

           function Get-CmdletAlias ($cmdletname)
           {
              get-alias | Where {$_.definition -like "*$cmdletname*"} | ft Definition, Name -auto
           }

    -- Add an Add-PsSnapin command to add any Windows PowerShell snap-ins that
       you use.

    -- Customize your console.

           function Color-Console
           {
            $host.ui.rawui.backgroundcolor = "white"
            $host.ui.rawui.foregroundcolor = "black"
                $hosttime = (dir $pshome\powershell.exe).creationtime
                $Host.UI.RawUI.WindowTitle = "Windows PowerShell $hostversion ($hosttime)"
                clear-host
           }
           Color-console

    -- Add a customized Windows PowerShell prompt that includes the computer
       name and the current path.

           function prompt
           {
              $env:computername + "\" + (get-location) + "> "
           }

       For more information about the Windows PowerShell prompt, see
       about_Prompts.

 THE NOPROFILE PARAMETER

    To start Windows Powershell without profiles, use the NoProfile parameter
    of PowerShell.exe, the program that starts Windows PowerShell.

    To begin, open a program that can start Windows PowerShell, such as Cmd.exe
    or Windows PowerShell itself. You can also use the Run dialog box in
    Windows.

    Type:

    powershell -noprofile

    For a complete list of the parameters of PowerShell.exe,
    type:

    powershell -?

 PROFILES AND EXECUTION POLICY

    The Windows PowerShell execution policy determines, in part, whether you
    can run scripts and load configuration files, including the profiles. The
    Restricted execution policy is the default. It prevents all scripts from
    running, including the profiles. If you use the Restricted policy, the
    profile does not run, and its contents are not applied.

    A Set-ExecutionPolicy command sets and changes your execution policy. It is
    one of the few commands that applies in all Windows PowerShell sessions
    because the value is saved in the registry. You do not have to set it when
    you open the console, and you do not have to store a Set-ExecutionPolicy
    command in your profile.

 PROFILES AND REMOTE SESSIONS

    Windows PowerShell profiles are not run automatically in remote sessions,
    so the commands that the profileS add are not present in the remote session.
    In addition, the $profile automatic variable is not populated in remote sessions.

    To run a profile in a session, use the Invoke-Command cmdlet.

    For example, the following command runs the CurrentUserCurrentHost profile from
    the local computer in the session in $s.

        invoke-command -session $s -filepath $profile

    The following command runs the CurrentUserCurrentHost profile from the remote
    computer in the session in $s. Because the $profile variable is not populated,
    the command uses the explicit path to the profile.

        invoke-command -session $s {invoke-expression "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"}

    After running this command, the commands that the profile adds to the session
    are available in $s.

SEE ALSO
    about_Automatic_Variables
    about_Functions
    about_Prompts
    about_Execution_Policies
    about_Signing
    about_Remote
    Set-ExecutionPolicy


about_Prompts

TOPIC
    about_Prompts

SHORT DESCRIPTION
    Describes the Prompt function and demonstrates how to create a custom
    Prompt function.

LONG DESCRIPTION
    The Windows PowerShell command prompt indicates that Windows PowerShell
    is ready to run a command:

    PS C:\>

    The Windows PowerShell prompt is determined by the Prompt function. You
    can customize the prompt by creating your own Prompt function. Then, you
    can save this function in your Windows PowerShell profile.

  The Prompt Function

      The Prompt function determines the appearance of the Windows PowerShell
      prompt. Windows PowerShell comes with a built-in Prompt function, but
      you can override it by defining your own Prompt function.

      The Prompt function has the following syntax:

      function prompt { <function-body> }

      The Prompt function must return an object, typically a string. We
      recommend that it return a string or an object that is formatted as a
      string. The string should fit on an 80-character line.

      For example:

      PS C:\> function prompt {"Hello, World > "}
          Hello, World >

      Like all functions, the Prompt function is stored in the Function: drive.
      To display the code in the current Prompt function, type:

      (get-item function:prompt).definition

      This command uses the Get-Item cmdlet to display the Prompt item in the
      Function: drive. Then, it uses dot notation to display the value of the
      Definition property of the Prompt function.

  The Default Prompt

      The default Windows PowerShell prompt is:

      PS>

      This prompt appears only when the prompt function generates an error or
      when the prompt function does not return a string or object.

          PS C:\> function prompt {$null}
          PS>

      Because Windows PowerShell comes with a built-in prompt, you usually do
      not see the default prompt until you write your own prompt function.

  The Built-in Prompt

      Windows PowerShell includes a built-in prompt function that creates the
      familiar prompts. The built-in prompt function is:

          function prompt
          {
              $(if (test-path variable:/PSDebugContext) { '[DBG]: ' }

              else { '' }) + 'PS ' + $(Get-Location) `

              + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> '
          }

      The function uses the Test-Path cmdlet to determine whether the
      $PSDebugContext automatic variable is populated. If $PSDebugContext is
      populated, you are in debugging mode, and "[DBG]" is added to the prompt,
      as follows:

      [DBG] PS C:\ps-test>

      If $PSDebugContext is not populated, the function adds "PS" to the
      prompt. And, the function uses the Get-Location cmdlet to get the current
      file system directory location. Then, it adds a right angle bracket (>).
      For example:

      PS C:\ps-test>

      If you are in a nested prompt, the function adds two angle brackets (>>)
      to the prompt. (You are in a nested prompt if the value of the
      $NestedPromptLevel automatic variable is greater than 1.)

      For example, when you are debugging in a nested prompt, the prompt
      resembles the following prompt:

      [DBG] PS C:\ps-test>>>

      The Enter-PSSession cmdlet prepends the name of the remote computer to
      the current Prompt function.  When you use the Enter-PSSession cmdlet to
      start a session with a remote computer, the command prompt changes to
      include the name of the remote computer. For example:

          PS Hello, World> Enter-PSSession Server01

          [Server01]: PS Hello, World>

      Other Windows PowerShell host applications and alternate shells might
      have their own custom command prompts.

      For more information about the $PSDebugContext and $NestedPromptLevel
      automatic variables, see about_Automatic_Variables.

  Customizing the Prompt

      To customize the prompt, write a new Prompt function. The function is not
      protected, so you can overwrite it.

      To write a prompt function, type the following:

      function prompt { }

      Then, between the curly braces, enter the commands or the string that
      creates your prompt.

      For example, the following prompt includes your computer name:

      function prompt {"PS [$env:COMPUTERNAME]> "}

      On the Server01 computer, the prompt resembles the following prompt:

      PS [Server01] >

      The following prompt function includes the current date and time:

      function prompt {"$(get-date)> "}

      The prompt resembles the following prompt:

      01/01/2008 17:49:47>

      You can also modify the default Prompt function:

          function prompt
          {
              $(if (test-path variable:/PSDebugContext) { '[DBG]: ' }

              else { '' }) + "$(get-date)" `

              + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> '
          }

      For example, the following modified Prompt function adds "[ADMIN]:" to
      the built-in Windows PowerShell prompt when Windows PowerShell is opened
      by using the "Run as administrator" option:

          function prompt
          {
              $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
              $principal = [Security.Principal.WindowsPrincipal] $identity

              $(if (test-path variable:/PSDebugContext) { '[DBG]: ' }

              elseif($principal.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
                  { "[ADMIN]: " }

              else { '' }) + 'PS ' + $(Get-Location) + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> '
          }

      When you start Windows PowerShell by using the "Run as administrator"
      option, a prompt that resembles the following prompt appears:

      [ADMIN]: PS C:\ps-test>

      The following Prompt function displays the history ID of the next
      command. To view the command history, use the Get-History
      cmdlet.

          function prompt
          {
             # The at sign creates an array in case only one history item exists.
             $history = @(get-history)
             if($history.Count -gt 0)
             {
                $lastItem = $history[$history.Count - 1]
                $lastId = $lastItem.Id
             }

             $nextCommand = $lastId + 1
             $currentDirectory = get-location
             "PS: $nextCommand $currentDirectory >"
          }

      The following prompt uses the Write-Host and Get-Random cmdlets to create
      a prompt that changes color randomly. Because Write-Host writes to the
      current host application but does not return an object, this function
      includes a Return statement. Without it, Windows PowerShell uses the
      default prompt, "PS>".

          function prompt
          {
              $color = get-random -min 1 -max 16
              write-host ("PS " + $(get-location) +">") -nonewline -foregroundcolor $color
              return " "
          }

  Saving the Prompt

      Like any function, the Prompt function applies only in the current
      session. To save the Prompt function for future sessions, add it to your
      Windows PowerShell profiles. For more information about profiles,
      see about_Profiles.

SEE ALSO
    Get-Location
    Enter-PSSession
    Get-History
    Get-Random
    Write-Host
    about_Profiles
    about_Functions
    about_Scopes
    about_Debuggers
    about_Automatic_Variables


about_Properties

TOPIC
    about_Properties

SHORT DESCRIPTION
    Describes how to use object properties in Windows PowerShell.

LONG DESCRIPTION
    Windows PowerShell uses structured collections of information called
    objects to represent the items in data stores or the state of the computer.
    Typically, you work with object that are part of the Microsoft .NET
    Framework, but you can also create custom objects in Windows PowerShell.

    The association between an item and its object is very close. When you
    change an object, you change the item that it represents. For example,
    when you get a file in Windows PowerShell, you do not get the actual file.
    Instead, you get a FileInfo object that represents the file. When you
    change the FileInfo object, the file changes too.

    Most objects have properties. Properties are the data that is associated
    with an object. This data describes the object. For example, a FileInfo
    object has a property called Length that describes the size of the file
    that is represented by the object.

  Object Properties

     To list the properties of an object, use the Get-Member cmdlet. For
     example, to get the properties of a FileInfo object, use the Get-ChildItem
     cmdlet to get the FileInfo object that represents a file. Then, use a
     pipeline operator (|) to send the FileInfo object to Get-Member. The
     following command gets the PowerShell.exe file and sends it to Get-Member.
     The $Pshome automatic variable contains the path of the Windows PowerShell
     installation directory.

         get-childitem $pshome\powershell.exe | get-member

     The output of the command lists the members of the FileInfo object.
     Members include both properties and methods. When you work in
     Windows PowerShell, you have access to all the members of the objects.

     To get only the properties of an object and not the methods, use the
     MemberType parameter of the Get-Member cmdlet with a value of "property",
     as shown in the following example.

         get-childitem $pshome\powershell.exe | get-member -membertype property

            TypeName: System.IO.FileInfo

         Name              MemberType Definition
         ----              ---------- ----------
         Attributes        Property   System.IO.FileAttributes Attributes {get;set;}
         CreationTime      Property   System.DateTime CreationTime {get;set;}
         CreationTimeUtc   Property   System.DateTime CreationTimeUtc {get;set;}
         Directory         Property   System.IO.DirectoryInfo Directory {get;}
         DirectoryName     Property   System.String DirectoryName {get;}
         Exists            Property   System.Boolean Exists {get;}
         Extension         Property   System.String Extension {get;}
         FullName          Property   System.String FullName {get;}
         IsReadOnly        Property   System.Boolean IsReadOnly {get;set;}
         LastAccessTime    Property   System.DateTime LastAccessTime {get;set;}
         LastAccessTimeUtc Property   System.DateTime LastAccessTimeUtc {get;set;}
         LastWriteTime     Property   System.DateTime LastWriteTime {get;set;}
         LastWriteTimeUtc  Property   System.DateTime LastWriteTimeUtc {get;set;}
         Length            Property   System.Int64 Length {get;}
         Name              Property   System.String Name {get;}

     After you find the properties, you can use them in your Windows PowerShell
     commands.

  Property Values

     Although every object of a specific type has the same properties, the
     values of those properties describe the particular object. For example,
     every FileInfo object has a CreationTime property, but the value of that
     property differs for each file.

     The most common way to get the values of the properties of an object is to
     use the dot method. Type a reference to the object, such as a variable
     that contains the object, or a command that gets the object. Then, type a
     dot (.) followed by the property name.

     For example, the following command displays the value of the CreationTime
     property of the PowerShell.exe file. The Get-ChildItem command returns a
     FileInfo object that represents the PowerShell.exe file. The command is
     enclosed in parentheses to make sure that it is executed before any
     properties are accessed. The Get-ChildItem command is followed by a dot
     and the name of the CreationTime property, as follows:

         C:\PS> (Get-ChildItem $pshome\powershell.exe).creationtime
         Tuesday, March 18, 2008 12:07:52 AM

     You can also save an object in a variable and then get its properties by
     using the dot method, as shown in the following example:

         C:\PS> $a = Get-ChildItem $pshome\powershell.exe
         C:\PS> $a.CreationTime
         Tuesday, March 18, 2008 12:07:52 AM

     You can also use the Select-Object and Format-List cmdlets to display the
     property values of an object. Select-Object and Format-List each have a
     Property parameter. You can use the Property parameter to specify one or
     more properties and their values. Or, you can use the wildcard
     character (*) to represent all the properties.

     For example, the following command displays the values of all the
     properties of the PowerShell.exe file.

         C:\PS> Get-ChildItem $pshome\powershell.exe | Format-List -property *

         PSPath            : Microsoft.PowerShell.Core\FileSystem::C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
         PSParentPath      : Microsoft.PowerShell.Core\FileSystem::C:\Windows\system32\WindowsPowerShell\v1.0
         PSChildName       : powershell.exe
         PSDrive           : C
         PSProvider        : Microsoft.PowerShell.Core\FileSystem
         PSIsContainer     : False
         VersionInfo       : File:             C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
                             InternalName:     POWERSHELL
                             OriginalFilename: PowerShell.EXE.MUI
                             File Version:      6.1.6570.1 (fbl_srv_powershell(nigels).070711-0102)
                             FileDescription:  PowerShell.EXE
                             Product:          Microsoft® Windows® Operating System
                             ProductVersion:   6.1.6570.1
                             Debug:            False
                             Patched:          False
                             PreRelease:       False
                             PrivateBuild:     True
                             SpecialBuild:     False
                             Language:         English (United States)

         BaseName          : powershell
         Mode              : -a---
         Name              : powershell.exe
         Length            : 160256
         DirectoryName     : C:\Windows\system32\WindowsPowerShell\v1.0
         Directory         : C:\Windows\system32\WindowsPowerShell\v1.0
         IsReadOnly        : False
         Exists            : True
         FullName          : C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
         Extension         : .exe
         CreationTime      : 3/18/2008 12:07:52 AM
         CreationTimeUtc   : 3/18/2008 7:07:52 AM
         LastAccessTime    : 3/19/2008 8:13:58 AM
         LastAccessTimeUtc : 3/19/2008 3:13:58 PM
         LastWriteTime     : 3/18/2008 12:07:52 AM
         LastWriteTimeUtc  : 3/18/2008 7:07:52 AM
         Attributes        : Archive

SEE ALSO
    about_Objects
    Get-Member
    Select-Object
    Format-List


about_Providers

TOPIC
    about_Providers

SHORT DESCRIPTION
    Describes how Windows PowerShell providers provide access to data and
    components that would not otherwise be easily accessible at the command
    line. The data is presented in a consistent format that resembles a file
    system drive.

LONG DESCRIPTION
    Windows PowerShell providers are Microsoft .NET Framework-based programs
    that make the data in a specialized data store available in Windows
    PowerShell so that you can view and manage it.

    The data that a provider exposes appears in a drive, and you access the
    data in a path like you would on a hard disk drive. You can use any of the
    built-in cmdlets that the provider supports to manage the data in the
    provider drive. And, you can use custom cmdlets that are designed
    especially for the data.

    The providers can also add dynamic parameters to the built-in cmdlets.
    These are parameters that are available only when you use the cmdlet with
    the provider data.

 BUILT-IN PROVIDERS
    Windows PowerShell includes a set of built-in providers that you can use
    to access the different types of data stores.

    Provider      Drive         Data store
    --------      -----         ----------
    Alias         Alias:        Windows PowerShell aliases

    Certificate   Cert:         x509 certificates for digital signatures

    Environment   Env:          Windows environment variables

    FileSystem    *             File system drives, directories, and files

    Function      Function:     Windows PowerShell functions

    Registry      HKLM:, HKCU   Windows registry

    Variable      Variable:     Windows PowerShell variables

    WSMan         WSMan         WS-Management configuration information

   * The FileSystem drives vary on each system.

    You can also create your own Windows PowerShell providers, and you can
    install providers that others develop. To list the providers that are
    available in your session, type:

       get-psprovider

 INSTALLING AND REMOVING PROVIDERS
    Windows PowerShell providers are delivered to you in Windows PowerShell
    snap-ins, which are .NET Framework-based programs that are compiled
    into .dll files. The snap-ins can include providers and cmdlets.

    Before you use the provider features, you have to install the snap-in and
    then add it to your Windows PowerShell session. For more information, see
    about_PsSnapins.

    You cannot uninstall a provider, although you can remove the Windows
    PowerShell snap-in for the provider from the current session. If you do,
    you will remove all the contents of the snap-in, including its cmdlets.

    To remove a provider from the current session, use the Remove-PsSnapin
    cmdlet. This cmdlet does not uninstall the provider, but it makes
    the provider unavailable in the session.

    You can also use the Remove-PsDrive cmdlet to remove any drive from the
    current session. This data on the drive is not affected, but the drive is
    no longer available in that session.

 VIEWING PROVIDERS
    To view the Windows PowerShell providers on your computer, type:

    get-psprovider

    The output lists the built-in providers and the providers that you added
    to the session.

 THE PROVIDER CMDLETS
    The following cmdlets are designed to work with the data exposed by
    any provider. You can use the same cmdlets in the same way to manage
    the different types of data that providers expose. After you
    learn to manage the data of one provider, you can use the same
    procedures with the data from any provider.

    For example, the New-Item cmdlet creates a new item. In the C: drive that
    is supported by the FileSystem provider, you can use New-Item to create a
    new file or folder. In the drives that are supported by the Registry
    provider, you can use New-Item to create a new registry key. In the Alias:
    drive, you can use New-Item to create a new alias.

    For detailed information about any of the following cmdlets, type:

        get-help <cmdlet-name> -detailed

    CHILDITEM CMDLETS
        Get-ChildItem

    CONTENT CMDLETS
        Add-Content
        Clear-Content
        Get-Content
        Set-Content

    ITEM CMDLETS
        Clear-Item
        Copy-Item
        Get-Item
        Invoke-Item
        Move-Item
        New-Item
        Remove-Item
        Rename-Item
        Set-Item

    ITEMPROPERTY CMDLETS
        Clear-ItemProperty
        Copy-ItemProperty
        Get-ItemProperty
        Move-ItemProperty
        New-ItemProperty
        Remove-ItemProperty
        Rename-ItemProperty
        Set-ItemProperty

    LOCATION CMDLETS
        Get-Location
        Pop-Location
        Push-Location
        Set-Location

    PATH CMDLETS
        Join-Path
        Convert-Path
        Split-Path
        Resolve-Path
        Test-Path

    PSDRIVE CMDLETS
        Get-PSDrive
        New-PSDrive
        Remove-PSDrive

    PSPROVIDER CMDLETS
        Get-PSProvider

 VIEWING PROVIDER DATA
    The primary benefit of a provider is that it exposes its data in a familiar
    and consistent way. The model for data presentation is a file system
    drive.

    To use data that the provider exposes, you view it, move through it,
    and change it as though it were data on a hard drive. Therefore, the most
    important information about a provider is the name of the drive
    that it supports.

    The drive is listed in the default display of the Get-PsProvider cmdlet,
    but you can get information about the provider drive by using the
    Get-PsDrive cmdlet. For example, to get all the properties of the
    Function: drive, type:

    get-psdrive Function | format-list *

    You can view and move through the data in a provider drive just as
    you would on a file system drive.

    To view the contents of a provider drive, use the Get-Item or Get-ChildItem
    cmdlets. Type the drive name followed by a colon (:). For example, to
    view the contents of the Alias: drive, type:

        get-item alias:

    You can view and manage the data in any drive from another drive by
    including the drive name in the path. For example, to view the
    HKLM\Software registry key in the HKLM: drive from another drive, type:

        get-childitem hklm:\software

    To open the drive, use the Set-Location cmdlet. Remember the colon
    when you specify the drive path. For example, to change your location
    to the root directory of the Cert: drive, type:

        set-location cert:

    Then, to view the contents of the Cert: drive, type:

    get-childitem

 MOVING THROUGH HIERARCHICAL DATA
    You can move through a provider drive just as you would a hard disk drive.
    If the data is arranged in a hierarchy of items within items, use a
    backslash (\) to indicate a child item. Use the following format:

    drive:\location\child-location\...

    For example, to change your location to the HKLM\Software registry key,
    type a Set-Location command, such as:

        set-location hklm:\software

    You can also use relative references to locations. A dot (.) represents the
    current location. For example, if you are in the HKLM:\Software\Microsoft
    registry key, and you want to list the registry subkeys in the
    HKLM:\Software\Micrsoft\PowerShell key, type the following command:

        get-childitem .\powershell

 FINDING DYNAMIC PARAMETERS
    Dynamic parameters are cmdlet parameters that are added to a cmdlet
    by a provider. These parameters are available only when the cmdlet is
    used with the provider that added them.

    For example, the Cert: drive adds the CodeSigningCert parameter
    to the Get-Item and Get-ChildItem cmdlets. You can use this parameter
    only when you use Get-Item or Get-ChildItem in the Cert: drive.

    For a list of the dynamic parameters that a provider supports, see the
    Help file for the provider. Type:

    get-help <provider-name>

    For example:

    get-help certificate

 LEARNING ABOUT PROVIDERS
    Although all provider data appears in drives, and you use the same methods
    to move through them, the similarity stops there. The data stores that
    the provider exposes can be as varied as Active Directory locations and
    Microsoft Exchange Server mailboxes.

    For information about individual Windows PowerShell providers, type:

    get-help <ProviderName>

    For example:

    get-help registry

    For a list of Help topics about the providers, type:

    get-help * -category provider

SEE ALSO
    about_Locations
    about_Path_Syntax


about_PSSessions

TOPIC
    about_PSSessions

SHORT DESCRIPTION
    Describes Windows PowerShell sessions (PSSessions) and explains how to
    establish a persistent connection to a remote computer.

LONG DESCRIPTION
    To run Windows PowerShell commands on a remote computer, you can use the
    ComputerName parameter of a cmdlet, or you can create a Windows PowerShell
    session (PSSession) and run commands in the PSSession.

    When you create a PSSession, Windows PowerShell establishes a persistent
    connection to the remote computer. Use a PSSession to run a series of
    related commands on a remote computer. Commands that run in the same
    PSSession can share data, such as the values of variables, aliases, and
    functions.

    You can also create a PSSession on the local computer and run commands
    in it. A local PSSession uses the Windows PowerShell remoting
    infrastructure to create and maintain the PSSession.

    This topic explains how to create, use, get, and delete PSSessions.
    For more advanced information, see about_PSSession_Details.

    Note: PSSessions use the Windows PowerShell remoting infrastructure.
          To use PSSessions, the local and remote computers must be configured
          for remoting. For more information, see about_Remote_Requirements.

          In Windows Vista and later versions of Windows, to create a
          PSSession on a local computer, you must start Windows PowerShell
          with the "Run as administrator" option.

 WHAT IS A SESSION?

    A session is an environment in which Windows PowerShell runs.

    Each time you start Windows PowerShell, a session is created for you, and
    you can run commands in the session. You can also add items to your session,
    such as modules and snap-ins, and you can create items, such as variables,
    functions, and aliases. These items exist only in the session and are
    deleted when the session ends.

    You can also create additional sessions, known as "Windows PowerShell
    sessions" or "PSSessions," on the local computer or on a remote computer.
    Like the default session, you can run commands in a PSSession and add and
    create items.

    However, unlike the session that starts automatically, you can control the
    PSSessions that you create. You can get, create, configure, and remove them,
    and you can run multiple commands in the same PSSession. The PSSession
    remains open and available until you delete it from your session.

    Typically, you create a PSSession to run a series of related commands on a
    remote computer. When you create a PSSession on a remote computer,
    Windows PowerShell establishes a persistent connection to the remote
    computer to support the session.

    If you use the computerName parameter of the Invoke-Command or
    Enter-PSSession cmdlet to run a remote command or to start an interactive
    session, Windows PowerShell creates a temporary session on the remote
    computer and closes the session as soon as the command is complete or as
    soon as the interactive session ends. You cannot control these temporary
    sessions, and you cannot use them for more than a single command or a
    single interactive session.

    In Windows PowerShell, the "current session" is the session that you are
    working in. The "current session" can refer to any session, including a
    temporary session or a PSSession.

 WHY USE A PSSESSION?

    Use a PSSession when you need a persistent connection to a remote computer.
    With a PSSession, you can run a series of commands that share data, such as
    the value of variables, the contents of a function, or the definition of an
    alias.

    You can run remote commands without creating a PSSession. Use the
    ComputerName parameter of remote-enabled cmdlets to run a single command
    or a series of unrelated commands on one or many computers.

    When you use the ComputerName parameter of Invoke-Expression or
    Enter-PSSession, Windows PowerShell establishes a temporary connection to
    the remote computer and then closes the connection as soon as the command
    is complete. Any data elements that you create are lost when the connection
    is closed.

    Other cmdlets that have a ComputerName parameter, such as Get-Eventlog and
    Get-WmiObject, use different remoting technologies to gather data. None
    create a persistent connection like a PSSession.

 HOW TO CREATE A PSSESSION

    To create a PSSession, use the New-PSSession cmdlet. To create the
    PSSession on a remote computer, use the ComputerName parameter of the
    New-PSSession cmdlet.

    For example, the following command creates a new PSSession on the
    Server01 computer.

        new-pssession -computername Server01

    When you submit the command, New-PSSession creates the PSSession and
    returns an object that represents the PSSession. You can save the object in
    a variable when you create the PSSession, or you can use a Get-PSSession
    command to get the PSSession at a later time.

    For example, the following command creates a new PSSession on the Server01
    computer and saves the resulting object in the $ps variable.

        $ps = new-pssession -computername Server01

 HOW TO CREATE PSSESSIONS ON MULTIPLE COMPUTERS

    To create PSSessions on multiple computers, use the ComputerName parameter
    of the New-PSSession cmdlet. Type the names of the remote computers in a
    comma-separated list.

    For example, to create PSSessions on the Server01, Server02, and Server03
    computers, type:

        new-PSSession -computername Server01, Server02, Server03

    New-PSSession creates one PSSession on each of the remote computers.

 HOW TO GET PSSESSIONS

    To get the PSSessions that were created in your current session, use the
    Get-PSSession cmdlet. Get-PSSession returns the same type of object that
    New-PSSession returns.

    The following command gets all the PSSessions that were created in the
    current session.

        get-PSSession

    The default display of the PSSessions shows their ID and a default display
    name. You can assign an alternate display name when you create the
    session.

        Id   Name       ComputerName    State    ConfigurationName
        ---  ----       ------------    -----    ---------------------
        1    Session1   Server01        Opened   Microsoft.PowerShell
        2    Session2   Server02        Opened   Microsoft.PowerShell
        3    Session3   Server03        Opened   Microsoft.PowerShell

    You can also save the PSSessions in a variable. The following command gets
    the PSSessions and saves them in the $ps123 variable.

        $ps123 = get-PSSession

    When using the PSSession cmdlets, you can refer to a PSSession by its ID, by
    its name, or by its instance ID (a GUID). The following command gets a
    PSSession by its ID and saves it in the $ps01 variable.

        $ps01 = get-PSSession -id 1

    Get-PSSession gets only the PSSessions that were created in the current
    session. It does not get PSSessions that were created in other sessions or
    on other computers, even if the sessions are connected to and are running
    commands on the local computer.

 HOW TO RUN COMMANDS IN A PSSESSION

    To run a command in one or more PSSessions, use the Invoke-Command cmdlet.
    Use the Session parameter to specify the PSSessions and the ScriptBlock
    parameter to specify the command.

    For example, to run a Get-ChildItem ("dir") command in each of the three
    PSSessions saved in the $ps123 variable, type:

        invoke-command -session $ps123 -scriptblock {get-childitem}

 HOW TO DELETE PSSESSIONS

    When you are finished with the PSSession, use the Remove-PSSession cmdlet
    to delete the PSSession and to release the resources that it was using.

        remove-PSSession -session $ps

        - or -

        remove-PSSession -id 1

    If you do not delete the PSSession, the PSSession remains open and
    available for use until you close the current session or until you exit
    Windows PowerShell.

    You can also use the TimeOut parameter of New-PSSession to set an
    expiration time for an idle PSSession. For more information,
    see new-PSSession.

 THE PSSESSION CMDLETS

    Cmdlet                Description
    -----------------     ------------------------------------------------------
    New-PSSession         Creates a new PSSession on a local or remote computer.

    Get-PSSession         Gets the PSSessions in the current session.

    Remove-PSSession      Deletes the PSSessions in the current session.

    Enter-PSSession       Starts an interactive session.

    Exit-PSSession        Ends an interactive session.

    For a list of PSSession cmdlets, type:

    get-help *-PSSession

 FOR MORE INFORMATION

    For more information about PSSessions, see about_PSSession_Details.

SEE ALSO
    about_Remote
    about_Remote_Requirements
    New-PSSession
    Get-PSSession
    Remove-PSSession
    Enter-PSSession
    Exit-PSSession
    Invoke-Command


about_PSSession_Details

TOPIC
    about_PSSession_Details

SHORT DESCRIPTION
    Provides detailed information about Windows PowerShell sessions and the
    role they play in remote commands.

LONG DESCRIPTION
    A session is an environment in which Windows PowerShell runs. A session is
    created for you whenever you start Windows PowerShell. You can create
    additional sessions, called "Windows PowerShell sessions" or "PSSessions"
    on your computer or another computer.

    Unlike the sessions that Windows PowerShell creates for you, you control
    and manage the PSSessions that you create.

    PSSessions play an important role in remote computing. When you create a
    PSSession that is connected to a remote computer, Windows PowerShell
    establishes a persistent connection to the remote computer to support the
    PSSession. You can use the PSSession to run a series of commands,
    functions, and scripts that share data.

    This topic provides detailed information about sessions and PSSessions
    in Windows PowerShell. For basic information about the tasks that you
    can perform with sessions, see about_PSSessions.

  ABOUT SESSIONS

    Technically, a session is an execution environment in which Windows
    PowerShell runs. Each session includes an instance of the
    System.Management.Automation engine and a host program in which Windows
    PowerShell runs. The host can be the familiar Windows PowerShell console
    or another program that runs commands, such as Cmd.exe, or a program built
    to host Windows PowerShell, such as Windows PowerShell Integrated Scripting
    Environment (ISE). From a Windows perspective, a session is a Windows
    process on the target computer.

    Each session is configured independently. It includes its own properties,
    its own execution policy, and its own profiles. The environment that exists
    when the session is created persists for its lifetime even if you change
    the environment on the computer. All sessions are created in a global
    scope, even sessions that you create in a script.

    You can run only one command (or command pipeline) in a session at one
    time. A second command run synchronously (one at a time) waits up to four
    minutes for the first command to be completed. A second command run
    asynchronously (concurrently) fails.

  ABOUT PSSESSIONS

    A session is created each time that you start Windows PowerShell. And,
    Windows PowerShell creates temporary sessions to run individual commands.
    However, you can also create sessions (called "Windows PowerShell sessions"
    or "PSSessions") that you control and manage.

    PSSessions are critical to remote commands. If you use the ComputerName
    parameter of the Invoke-Command or Enter-PSSession cmdlets, Windows
    PowerShell establishes a temporary session to run the command and then
    closes the session as soon as the command or the interactive session
    is complete.

    However, if you use the New-PSSession cmdlet to create a PSSession, Windows
    PowerShell establishes a persistent session on the remote computer in which
    you can run multiple commands or interactive sessions. The PSSessions that
    you create remain open and available for use until you delete them or until
    you close the session in which they were created.

    When you create a PSSession on a remote computer, the system creates a
    PowerShell process on the remote computer and establishes a connection
    from the local computer to the process on the remote computer. When you
    create a PSSession on the local computer, both the new process and the
    connections are created on the local computer.

  WHEN DO I NEED A PSSESSION?

    The Invoke-Command and Enter-PSSession cmdlets have both ComputerName and
    Session parameters. You can use either to run a remote command.

    Use the ComputerName parameter to run a single command or a series of
    unrelated commands on one or many computers.

    To run commands that share data, you need a persistent connection to the
    remote computer. In that case, create a PSSession, and then use the Session
    parameter to run commands in the PSSession.

    Many other cmdlets that get data from remote computers, such as
    Get-Process, Get-Service, Get-EventLog, and Get-WmiObject have only a
    ComputerName parameter. They use technologies other than Windows PowerShell
    remoting to gather data remotely. These cmdlets do not have a Session
    parameter, but you can use the Invoke-Command cmdlet to run these commands
    in a PSSession.

  HOW DO I CREATE A PSSESSION?

    To create a PSSession, use the New-PSSession cmdlet. You can use
    New-PSSession to create a PSSession on a local or remote computer.

  CAN I CREATE A PSSESSION ON ANY COMPUTER?

    To create a PSSession that is connected to a remote computer, the computer
    must be configured for remoting in Windows PowerShell. The current user
    must be a member of the Administrators group on the remote computer, or
    the current user must be able to supply the credentials of a member of
    the Administrators group. For more information,
    see about_Remote_Requirements.

  CAN I SEE THE PSSESSIONS THAT OTHERS HAVE CREATED ON MY COMPUTER?

    No. You can get and manage only the PSSessions that you have created in the
    current session. You cannot see PSSessions that others have created, even
    if they run commands on the local computer.

  CAN I RUN A BACKGROUND JOB IN A PSSESSION?

    Yes. A background job is a command that runs asynchronously in the
    background without interacting with the current session. When you submit
    a command to start a job, the command returns a job object, but the job
    continues to run in the background until it is complete.

    To start a background job on a local computer, use the Start-Job command.
    You can run the background job in a temporary connection (by using the
    ComputerName parameter) or in a PSSession (by using the Session parameter).

    To start a background job on a remote computer, use the Invoke-Command
    cmdlet with its AsJob parameter, or use the Invoke-Command cmdlet to run a
    Start-Job command on a remote computer. When using the AsJob parameter,
    you can use the ComputerName or Session parameters.

    When using Invoke-Command to run a Start-Job command, you must run the
    command in a PSSession. If you use the ComputerName parameter, Windows
    PowerShell ends the connection when the job object returns, and the job is
    interrupted.

    For more information, see about_Jobs.

  CAN I RUN AN INTERACTIVE SESSION?

    Yes. To start an interactive session with a remote computer, use the
    Enter-PSSession cmdlet. In an interactive session, the commands that you
    type run on the remote computer, just as if you typed them directly on the
    remote computer.

    You can run an interactive session in a temporary session (by using the
    ComputerName parameter) or in a PSSession (by using the Session parameter).
    If you use a PSSession, the PSSession retains the data from previous
    commands, and the PSSession retains any data generated during the
    interactive session for use in later commands.

    When you end the interactive session, the PSSession remains open and
    available for use.

    For more information, see Enter-PSSession and Exit-PSSession.

  MUST I DELETE THE PSSESSIONS?

    Yes. A PSSession is a process, which is a self-contained environment that
    uses memory and other resources even when you are not using it. When you are
    finished with a PSSession, delete it. If you create multiple PSSessions,
    close the ones that you are not using, and maintain only the ones currently
    in use.

    To delete PSSessions, use the Remove-PSSession cmdlet. It deletes the
    PSSessions and releases all of the resources that they were using.

    You can also use the TimeOut parameter of New-PSSession to close an idle
    PSSession after an interval that you specify. For more information,
    see New-PSSession.

    If you do not delete the PSSession or set a time-out, the PSSession remains
    open and available for use until you close it, until you close the session
    in which it was created, or until you exit Windows PowerShell. However, a
    PSSession on a remote computer will be disconnected if the remote computer
    does not respond for four minutes. (The remote computer is configured to
    send a heartbeat pulse every three minutes.)

    If you save a PSSession object in a variable and then delete the PSSession
    or let it time out, the variable still contains the PSSession object, but
    the PSSession is not active and cannot be used or repaired.

  ARE ALL SESSIONS AND PSSESSIONS ALIKE?

    No. Developers can create custom sessions that include only selected
    providers and cmdlets. If a command works in one session but not in
    another, it might be because the session is restricted.

SEE ALSO
    about_Jobs
    about_PSSessions
    about_Remote
    about_Remote_Requirements
    Invoke-Command
    New-PSSession
    Get-PSSession
    Remove-PSSession
    Enter-PSSession
    Exit-PSSession


about_PSSnapins

TOPIC
    about_PSSnapins

SHORT DESCRIPTION
    Describes Windows PowerShell snap-ins and shows how to use and manage them.

LONG DESCRIPTION
    A Windows PowerShell snap-in is a Microsoft .NET Framework assembly that
    contains Windows PowerShell providers and/or cmdlets. Windows PowerShell
    includes a set of basic snap-ins, but you can extend the power and value
    of Windows PowerShell by adding snap-ins that contain providers and cmdlets
    that you create or get from others.

    When you add a snap-in, the cmdlets and providers that it contains are
    immediately available for use in the current session, but the change
    affects only the current session.

    To add the snap-in to all future sessions, save it in your Windows
    PowerShell profile. You can also use the Export-Console cmdlet to save
    the snap-in names to a console file and then use it in future sessions.
    You can even save multiple console files, each with a different set of
    snap-ins.

 BUILT-IN SNAP-INS
    Windows PowerShell includes a set of Windows PowerShell snap-ins that
    contain the built-in providers and cmdlets.

    Microsoft.PowerShell.Core
        Contains providers and cmdlets used to manage the basic features of
        Windows PowerShell. It includes the FileSystem, Registry, Alias,
        Environment, Function, and Variable providers and basic cmdlets like
        Get-Help, Get-Command, and Get-History.

    Microsoft.PowerShell.Host
       Contains cmdlets used by the Windows PowerShell host, such as
       Start-Transcript and Stop-Transcript.

    Microsoft.PowerShell.Management
        Contains cmdlets such as Get-Service and Get-ChildItem that are used to
        manage Windows-based features.

    Microsoft.PowerShell.Security
        Contains cmdlets used to manage Windows PowerShell security, such as
        Get-Acl, Get-AuthenticodeSignature, and ConvertTo-SecureString.

    Microsoft.PowerShell.Utility
        Contains cmdlets used to manipulate objects and data, such as
        Get-Member, Write-Host, and Format-List.

 FINDING SNAP-INS
    To get a list of the Windows PowerShell snap-ins on your computer, type:

    get-pssnapin

    To get the snap-in for each Windows PowerShell provider, type:

        get-psprovider | format-list name, pssnapin

    To get a list of the cmdlets in a Windows PowerShell snap-in, type:

        get-command -module <snap-in_name>

 INSTALLING A SNAP-IN
    The built-in snap-ins are registered in the system and added to the
    default session when you start Windows PowerShell. However, you have to
    register snap-ins that you create or obtain from others and then add the
    snap-ins to your session.

 REGISTERING A SNAP-IN
    A Windows PowerShell snap-in is a program written in a .NET Framework
    language that is compiled into a .dll file. To use the providers and
    cmdlets in a snap-in, you must first register the snap-in (add it to the
    registry).

    Most snap-ins include an installation program (an .exe or .msi file)
    that registers the .dll file for you. However, if you receive a snap-in as
    a .dll file, you can register it on your system. For more information, see
    "How to Register Cmdlets, Providers, and Host Applications" in the MSDN
    (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkID=143619.

    To get all the registered snap-ins on your system or to verify that a
    snap-in is registered, type:

    get-pssnapin -registered

 ADDING THE SNAP-IN TO THE CURRENT SESSION
    To add a registered snap-in to the current session, use the Add-PsSnapin
    cmdlet. For example, to add the Microsoft SQL Server snap-in to the
    session, type:

    add-pssnapin sql

    After the command is completed, the providers and cmdlets in the snap-in
    are available in the session. However, they are available only in the
    current session unless you save them.

 SAVING THE SNAP-INS
    To use a snap-in in future Windows PowerShell sessions, add the
    Add-PsSnapin command to your Windows PowerShell profile. Or, export
    the snap-in names to a console file.

    If you add the Add-PSSnapin command to your profile, it is available
    in all future Windows PowerShell sessions. If you export the names of
    the snap-ins in your session, you can use the export file only when you
    need the snap-ins.

    To add the Add-PsSnapin command to your Windows PowerShell profile,
    open your profile, paste or type the command, and then save the profile.
    For more information, see about_Profiles.

    To save the snap-ins from a session in console file (.psc1), use
    the Export-Console cmdlet. For example, to save the snap-ins in
    the current session configuration to the NewConsole.psc1 file in the
    current directory, type:

    export-console NewConsole

    For more information, see Export-Console.

 OPENING WINDOWS POWERSHELL WITH A CONSOLE FILE
    To use a console file that includes the snap-in, start Windows PowerShell
    (Powershell.exe) from the command prompt in Cmd.exe or in another
    Windows PowerShell session. Use the PsConsoleFile parameter to specify
    the console file that includes the snap-in. For example, the following
    command starts Windows PowerShell with the NewConsole.psc1 console file:

    powershell.exe -psconsolefile NewConsole.psc1

    The providers and cmdlets in the snapin are now available for use in
    the session.

 REMOVING A SNAP-IN
    To remove a Windows PowerShell snap-in from the current session, use the
    Remove-PsSnapin cmdlet. For example, to remove the SQL Server
    snap-in from the current session, type:

    remove-pssnapin sql

    This cmdlet removes the snap-in from the session. The snap-in is still
    loaded, but the providers and cmdlets that it supports are no longer
    available.

SEE ALSO
    Add-PsSnapin
    Get-PsSnapin
    Remove-PsSnapin
    Export-Console
    Get-Command
    about_Profiles


about_Quoting_Rules

TOPIC
    about_Quoting_Rules

SHORT DESCRIPTION
    Describes rules for using single and double quotation marks
    in Windows PowerShell.

LONG DESCRIPTION
    Quotation marks are used to specify a literal string. You can enclose a
    string in single quotation marks (') or double quotation marks (").

    Quotation marks are also used to create a here-string. A here-string is a
    single-quoted or double-quoted string in which quotation marks are
    interpreted literally. A here-string can span multiple lines. All the
    lines in a here-string are interpreted as strings, even though they are
    not enclosed in quotation marks.

    In commands to remote computers, quotation marks define the parts of
    the command that are run on the remote computer. In a remote session,
    quotation marks also determine whether the variables in a command are
    interpreted first on the local computer or on the remote computer.

 Single and Double-Quoted Strings

      When you enclose a string in double quotation marks (a double-quoted
      string), variable names that are preceded by a dollar sign ($) are
      replaced with the variable's value before the string is passed to the
      command for processing.

      For example:

          $i = 5
          "The value of $i is $i."

      The output of this command is:

          The value of 5 is 5.

      Also, in a double-quoted string, expressions are evaluated, and the
      result is inserted in the string. For example:

      "The value of $(2+3) is 5."

      The output of this command is:

      The value of 5 is 5.

      When you enclose a string in single-quotation marks (a single-quoted
      string), the string is passed to the command exactly as you type it.
      No substitution is performed. For example:

          $i = 5
          'The value of $i is $i.'

      The output of this command is:

          The value $i is $i.

      Similarly, expressions in single-quoted strings are not evaluated. They
      are interpreted as literals. For example:

      'The value of $(2+3) is 5.'

      The output of this command is:

      The value of $(2+3) is 5.

      To prevent the substitution of a variable value in a double-quoted
      string, use the backtick character (`)(ASCII 96), which is the
      Windows PowerShell escape character.

      In the following example, the backtick character that precedes the first
      $i variable prevents Windows PowerShell from replacing the variable name
      with its value. For example:

          $i = 5
          "The value of `$i is $i."

      The output of this command is:

          The value $i is 5.

      To make double-quotation marks appear in a string, enclose the entire
      string in single quotation marks. For example:

          'As they say, "live and learn."'

      The output of this command is:

          As they say, "live and learn."

      You can also enclose a single-quoted string in a double-quoted string.
      For example:

          "As they say, 'live and learn.'"

      The output of this command is:

          As they say, 'live and learn.'

      Or, double the quotation marks around a double-quoted phrase. For
      example:

          "As they say, ""live and learn."""

      The output of this command is:

          As they say, "live and learn."

      To include a single quotation mark in a single-quoted string, use a
      second consecutive single quote. For example:

          'don''t'

      The output of this command is:

          don't

      To force Windows PowerShell to interpret a double quotation mark
      literally, use a backtick character. This prevents Windows PowerShell
      from interpreting the quotation mark as a string delimiter. For example:

          "Use a quotation mark (`") to begin a string."

      Because the contents of single-quoted strings are
      interpreted literally, you cannot use the backtick character to
      force a literal character interpretation in a single-quoted string.

      For example, the following command generates an error because Windows
      PowerShell does not recognize the escape character. Instead, it
      interprets the second quotation mark as the end of the string.

      PS C:\> 'Use a quotation mark (`') to begin a string.'
          Unexpected token ')' in expression or statement.
          At line:1 char:27
          + 'Use a quotation mark (`') <<<<  to begin a string.'

 Single and Double-Quoted Here-Strings

      The quotation rules for here-strings are slightly different.

      A here-string is a single-quoted or double-quoted string in
      which quotation marks are interpreted literally. A here-string can
      span multiple lines. All the lines in a here-string are interpreted
      as strings even though they are not enclosed in quotation marks.

      Like regular strings, variables are replaced by their values in
      double-quoted here-strings. In single-quoted here-strings, variables
      are not replaced by their values.

      You can use here-strings for any text, but they are particularly
      useful for the following kinds of text:

          - Text that contains literal quotation marks
          - Multiple lines of text, such as the text in an HTML or XML document
          - The Help text for a script or function

      A here-string can have either of the following formats, where <Enter>
      represents the linefeed or newline hidden character that is added when
      you press the ENTER key.

      Format 1:

      @"<Enter>
          <string> [string] ...<Enter>
          "@

      Format 2:

      @'<Enter>
          <string> [string] ...<Enter>
          '@

      In either format, the closing quotation mark must be the first character
      in the line.

      A here-string contains all the text between the two hidden characters.
      In the here-string, all quotation marks are interpreted literally.
      For example:

      @"
      For help, type "get-help"
      "@

      The output of this command is:

      For help, type "get-help"

      Using a here-string can simplify using a string in a command. For
      example:

      @"
          Use a quotation mark (') to begin a string.
          "@

      The output of this command is:

          Use a quotation mark (') to begin a string.

      In single-quoted here-strings, variables are interpreted literally and
      reproduced exactly. For example:

          @'
      The $profile variable contains the path
          of your Windows PowerShell profile.
          '@

      The output of this command is:

      The $profile variable contains the path
          of your Windows PowerShell profile.

      In double-quoted here-strings, variables are replaced by their values.
      For example:

      @"
          Even if you have not created a profile,
          the path of the profile file is:
          $profile.
          "@

      The output of this command is:

      Even if you have not created a profile,
      the path of the profile file is:
      C:\Users\User01\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.

      Here-strings are typically used to assign multiple lines to
      a variable. For example, the following here-string assigns a
      page of XML to the $page variable.

        $page = [XML] @"
        <command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10"
        xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10"
        xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
        <command:details>
                <command:name>
                       Format-Table
            </command:name>
            <maml:description>
            <maml:para>Formats the output as a table.</maml:para>
            </maml:description>
            <command:verb>format</command:verb>
            <command:noun>table</command:noun>
            <dev:version></dev:version>
         </command:details>
        ...
        </command:command>
        "@

      Here-strings are also a convenient format for input to the
      ConvertFrom-StringData cmdlet, which converts here-strings to hash
      tables. For more information, see ConvertFrom-StringData.

SEE ALSO
    about_Escape_Characters
    ConvertFrom-StringData


about_Redirection

TOPIC
    about_Redirection

SHORT DESCRIPTION
    Describes how to redirect output from Windows PowerShell to text files.

LONG DESCRIPTION
    By default, Windows PowerShell sends its command output to the Windows
    PowerShell console. However, you can direct the output to a text
    file, and you can redirect error output to the regular output stream.

    You can use the following methods to redirect output:

        - Use the Out-File cmdlet, which sends command output to a text file.
          Typically, you use the Out-File cmdlet when you need to use its
          parameters, such as the Encoding, Force, Width, or NoClobber
          parameters.

        - Use the Tee-Object cmdlet, which sends command output to a text file
          and then sends it to the pipeline.

        - Use the Windows PowerShell redirection operators.

      The Windows PowerShell redirection operators are as follows.

      Operator  Description                Example
      --------  ----------------------     ------------------------------
      >         Sends output to the        get-process > process.txt
                specified file.

      >>        Appends the output to      dir *.ps1 >> scripts.txt
                the contents of the
                specified file.

      2>        Sends errors to the        get-process none 2> errors.txt
                specified file.

      2>>       Appends the errors to      get-process none 2>> save-errors.txt
                the contents of the
                specified file.

      2>&1      Sends errors to the        get-process none, powershell 2>&1
                success output stream.

    The syntax of the redirection operators is as follows:

       <input> <operator> [<path>\]<file>

    If the specified file already exists, the redirection operators that do not
    append data (> and 2>) overwrite the current contents of the file without
    warning. However, if the file is a read-only, hidden, or system file, the
    redirection fails. The append redirection operators (>> and 2>>) do not
    write to a read-only file, but they append content to a system or hidden
    file.

    To force the redirection of content to a read-only, hidden, or system file,
    use the Out-File cmdlet with its Force parameter. When you are writing to
    files, the redirection operators use Unicode encoding. If the file has a
    different encoding, the output might not be formatted correctly. To
    redirect content to non-Unicode files, use the Out-File cmdlet with its
    Encoding parameter.

SEE ALSO
    Out-File
    Tee-Object
    about_Operators
    about_Command_Syntax
    about_Path_Syntax


about_Ref

TOPIC
    about_Ref

SHORT DESCRIPTION
    Describes how to create and use a reference variable type.

LONG DESCRIPTION
    You can use the reference variable type to permit a method to change the
    value of a variable that is passed to it.

    When the [ref] type is associated with an object, it returns a reference
    to that object. If the reference is used with a method, the method can
    refer to the object that was passed to it. If the object is changed within
    the method, the change appears as a change in the value of the variable
    when control returns to the calling method.

    To use referencing, the parameter must be a reference variable. If it is
    not, an InvalidArgument exception is thrown.

    The parameters used in method invocations must match the type required
    by the methods.

    Examples:

        PS> function swap([ref]$a,[ref]$b)
        >> {
        >>     $a.value,$b.value = $b.value,$a.value
        >> }

        PS> $a = 1
        PS> $b = 10
        PS> $a,$b
        1
        10
        PS> swap ([ref]$a) ([ref]$b)
        PS> $a,$b
        10
        1

        PS C:\ps-test> function double
        >> {
        >>     param ([ref]$x) $x.value = $x.value * 2
        >> }

        PS C:> $number = 8
        PS C:> $number
        8
        PS C> double ([ref]$number)
        PS C> $number
        16

        The variable must be a reference variable.

        PS C:\ps-test> double $number
        double : Reference type is expected in argument.
        At line:1 char:7
        + double  <<<< $number

SEE ALSO
    about_Variables
    about_Environment_Variables
    about_Functions
    about_Script_Blocks


about_Regular_Expressions

TOPIC
    about_Regular_Expressions

SHORT DESCRIPTION
    Describes regular expressions in Windows PowerShell.

LONG DESCRIPTION
    Windows PowerShell supports the following regular expression characters.

        Format   Logic                            Example
        -------- -------------------------------  -----------------------
        value    Matches exact characters         "book" -match "oo"
                 anywhere in the original value.

        .        Matches any single character.    "copy" -match "c..y"

        [value]  Matches at least one of the      "big" -match "b[iou]g"
                 characters in the brackets.

        [range]  Matches at least one of the      "and" -match "[a-e]nd"
                 characters within the range.
                 The use of a hyphen (–) allows
                 you to specify an adjacent
                 character.

        [^]      Matches any characters except    "and" -match "[^brt]nd"
                 those in brackets.

        ^        Matches the beginning            "book" -match "^bo"
                 characters.

        $        Matches the end characters.      "book" -match "ok$"

        *        Matches any instances            "baggy" -match "g*"
                 of the preceding character.

        ?        Matches one instance             "baggy" -match "g?"
                 of the preceding character.

        \        Matches the character that       "Try$" -match "Try\$"
                 follows as an escaped character.

    Windows PowerShell supports the character classes available in
    Microsoft .NET Framework regular expressions.

        Format   Logic                            Example
        -------- -------------------------------  -----------------------
        \p{name} Matches any character in the     "abcd defg" -match "\p{Ll}+"
                 named character class specified
                 by {name}. Supported names are
                 Unicode groups and block
                 ranges such as Ll, Nd,
                 Z, IsGreek, and IsBoxDrawing.

        \P{name} Matches text not included in     1234 -match "\P{Ll}+"
                 the groups and block ranges
                 specified in {name}.

        \w       Matches any word character.      "abcd defg" -match "\w+"
                 Equivalent to the Unicode        (this matches abcd)
                 character categories [\p{Ll}
                 \p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}].
                 If ECMAScript-compliant behavior
                 is specified with the ECMAScript
                 option, \w is equivalent to
                 [a-zA-Z_0-9].

        \W       Matches any nonword character.   "abcd defg" -match "\W+"
                 Equivalent to the Unicode        (This matches the space)
                 categories [^\p{Ll}\p{Lu}\p{Lt}
                 \p{Lo}\p{Nd}\p{Pc}].

        \s       Matches any white-space          "abcd defg" -match "\s+"
                 character.  Equivalent to the
                 Unicode character categories
                 [\f\n\r\t\v\x85\p{Z}].

        \S       Matches any non-white-space      "abcd defg" -match "\S+"
                 character. Equivalent to the
                 Unicode character categories
                 [^\f\n\r\t\v\x85\p{Z}].

        \d       Matches any decimal digit.       12345 -match "\d+"
                 Equivalent to \p{Nd} for
                 Unicode and [0-9] for non-
                 Unicode behavior.

        \D       Matches any nondigit.            "abcd" -match "\D+"
                 Equivalent  to \P{Nd} for
                 Unicode and [^0-9] for non-
                 Unicode behavior.

    Windows PowerShell supports the quantifiers available in .NET Framework
    regular expressions. The following are some examples of quantifiers.

        Format   Logic                            Example
        -------- -------------------------------  -----------------------
        *        Specifies zero or more matches;  "abc" -match "\w*"
                 for example, \w* or (abc)*.
                 Equivalent to {0,}.

        +        Matches repeating instances of   "xyxyxy" -match "xy+"
                 the preceding characters.

        ?        Specifies zero or one matches;   "abc" -match "\w?"
                 for example, \w? or (abc)?.
                 Equivalent to {0,1}.

        {n}      Specifies exactly n matches;     "abc" -match "\w{2}"
                 for example, (pizza){2}.

        {n,}     Specifies at least n matches;    "abc" -match "\w{2,}"
                 for example, (abc){2,}.

        {n,m}    Specifies at least n, but no     "abc" -match "\w{2,3}"
                 more than m, matches.

    All the comparisons shown in the preceding table evaluate to true.

    Notice that the escape character for regular expressions, a backslash (\),
    is different from the escape character for Windows PowerShell. The
    escape character for Windows PowerShell is the backtick character (`)
    (ASCII 96).

    For more information, see the "Regular Expression Language Elements" topic
    in the Microsoft Developer Network (MSDN) library
    at http://go.microsoft.com/fwlink/?LinkId=133231.

SEE ALSO
    about_Comparison_Operators
    about_Operators


about_Remote

TOPIC
    about_Remote

SHORT DESCRIPTION
    Describes how to run remote commands in Windows PowerShell.

LONG DESCRIPTION
    You can run remote commands on a single computer or on multiple
    computers by using a temporary or persistent connection. You can also
    start an interactive session with a single remote computer.

    This topic provides a series of examples to show you how to
    run different types of remote command. After you try these basic
    commands, read the Help topics that describe each cmdlet that is
    used in these commands. The topics provide the details and explain
    how you can modify the commands to meet your needs.

    Note: To use Windows PowerShell remoting, the local and remote computers
          must be configured for remoting. For more information, see
          about_Remote_Requirements.

 HOW TO START AN INTERACTIVE SESSION (ENTER-PSSESSION)

     The easiest way to run remote commands is to start an
     interactive session with a remote computer.

     When the session starts, the commands that you type run on the
     remote computer, just as though you typed them directly
     on the remote computer. You can connect to only one
     computer in each interactive session.

     To start an interactive session, use the Enter-PSSession
     cmdlet. The following command starts an interactive session
     with the Server01 computer:

    enter-pssession server01

     The command prompt changes to indicate that you are connected
     to the Server01 computer.

    Server01\PS>

     Now, you can type commands on the Server01 computer.

     To end the interactive session, type:

    exit-pssession

     For more information, see Enter-PSSession.

 HOW TO USE CMDLETS THAT HAVE A COMPUTERNAME PARAMETER TO GET REMOTE DATA

    Several cmdlets have a ComputerName parameter that lets you
    get objects from remote computers.

    Because these cmdlets do not use WS-Management-based Windows PowerShell
    remoting, you can use the ComputerName parameter of these cmdlets on any
    computer that is running Windows PowerShell. The computers do not have to
    be configured for Windows PowerShell remoting, and the computers do not
    have to meet the system requirements for remoting.

    The following cmdlets have a ComputerName parameter:

        Clear-EventLog    Limit-EventLog
        Get-Counter       New-EventLog
        Get-EventLog      Remove-EventLog
        Get-HotFix        Restart-Computer
        Get-Process       Show-EventLog
        Get-Service       Show-Service
        Get-WinEvent      Stop-Computer
        Get-WmiObject     Write-EventLog

    For example, the following command gets the services on
    the Server01 remote computer:

    get-service -computername server01

    Typically, cmdlets that support remoting without special configuration
    have a ComputerName parameter and do not have a Session parameter. To
    find these cmdlets in your session, type:

        get-command | where { $_.parameters.keys -contains "ComputerName" -and $_.parameters.keys -notcontains "Session"}

 HOW TO RUN A REMOTE COMMAND

    To run other commands on remote computers, use the
    Invoke-Command cmdlet.

    To run a single command or a few unrelated commands, use the
    ComputerName parameter of Invoke-Command to specify the remote
    computers. Use the ScriptBlock parameter to specify the command.

    For example, the following command runs a Get-Culture command
    on the Server01 computer.

    invoke-command -computername Server01 -scriptblock {get-culture}

    The ComputerName parameter is designed for situation in which you run
    a single command or several unrelated commands on one or many computers.
    To establish a persistent connection to a remote computer, use
    the Session parameter.

 HOW TO CREATE A PERSISTENT CONNECTION (PSSESSION)

    When you use the ComputerName parameter of the Invoke-Command
    cmdlet, Windows PowerShell establishes a connection just for the
    command. Then, it closes the connection when the command is complete. Any
    variables or functions that are defined in the command are lost.

    To create a persistent connection to a remote computer, use the
    New-PSSession cmdlet. For example, the following command creates
    PSSessions on the Server01 and Server02 computers and then saves the
    PSSessions in the $s variable.

    $s = new-pssession -computername Server01, Server02

 HOW TO RUN COMMANDS IN A PSSESSION

    With a PSSession, you can run a series of remote commands that
    share data, like functions, aliases, and the values of variables.
    To run commands in a PSSession, use the Session parameter of the
    Invoke-Command cmdlet.

    For example, the following command uses the Invoke-Command cmdlet
    to run a Get-Process command in the PSSessions on the Server01
    and Server02 computers. The command saves the processes in a $p
    variable in each PSSession.

        invoke-command -session $s -scriptblock {$p = get-process}

    Because the PSSession uses a persistent connection, you can run
    another command in the same PSSession that uses the $p variable.
    The following command counts the number of processes saved in $p.

        invoke-command -session $s -scriptblock {$p.count}

 HOW TO RUN A REMOTE COMMAND ON MULTIPLE COMPUTERS

    To run a remote command on multiple computers, type all of
    the computer names in the value of the ComputerName parameter of
    Invoke-Command. Separate the names with commas.

    For example, the following command runs a Get-Culture command
    on three computers:

    invoke-command -computername S1, S2, S3 -scriptblock {get-culture}

    You can also run a command in multiple PSSessions. The following
    commands create PSSessions on the Server01, Server02, and Server03
    computers and then run a Get-Culture command in each of the PSSessions.

        $s = new-pssession -computername S1, S2, S3
    invoke-command -session $s -scriptblock {get-culture}

    To include the local computer list of computers, type the name of
    the local computer, type a dot (.), or type  "localhost".

    invoke-command -computername S1, S2, S3, localhost -scriptblock {get-culture}

 HOW TO RUN A SCRIPT ON REMOTE COMPUTERS

    To run a local script on remote computers, use the
    FilePath parameter of Invoke-Command.

    For example, the following command runs the Sample.ps1 script
    on the S1 and S2 computers:

        invoke-command -computername S1, S2 -filepath C:\Test\Sample.ps1

    The results of the script are returned to the local computer. You
    do not need to copy any files.

 HOW TO STOP A REMOTE COMMAND

   To interrupt a command, press CTRL+C. The interrupt request is
   passed to the remote computer where it terminates the remote command.

FOR MORE INFORMATION

    -- For information about the system requirements for remoting,
       see about_Remote_Requirements.

    -- For help in formatting remote output, see about_Remote_Output.

    -- For information about how remoting works, how to manage remote
       data, special configurations, security issues, and other frequently
       asked questions, see about_Remote_FAQ.

    -- For help in resolving remoting errors, see about_Remote_Troubleshooting.

    -- For information about PSSessions and persistent connections, see
       about_PSSessions.

    -- For information about Windows PowerShell background jobs, see
       about_Jobs.

KEYWORDS
    about_Remoting

SEE ALSO
    about_PSSessions
    about_Remote_Requirements
    about_Remote_FAQ
    about_Remote_TroubleShooting
    Enter-PSSession
    Invoke-Command
    New-PSSession


about_Remote_FAQ

TOPIC
    about_Remote_FAQ

SHORT DESCRIPTION
    Contains questions and answers about running remote commands
    in Windows PowerShell.

LONG DESCRIPTION
   When you work remotely, you type commands in Windows PowerShell on one
   computer (known as the "local computer"), but the commands run on another
   computer (known as the "remote computer"). The experience of working
   remotely should be as much like working directly at the remote computer
   as possible.

    Note: To use Windows PowerShell remoting, the remote computer
          must be configured for remoting. For more information, see
          about_Remote_Requirements.

 MUST BOTH COMPUTERS HAVE WINDOWS POWERSHELL INSTALLED?

   Yes. To work remotely, the local and remote computers must have
   Windows PowerShell, the Microsoft .NET Framework 2.0, and the Web
   Services for Management (WS-Management) protocol. Any files and
   other resources that are needed to execute a particular command
   must be on the remote computer.

   You must have permission to connect to the remote computer, permission
   to run Windows PowerShell, and permission to access data stores (such as
   files and folders), and the registry on the remote computer.

   For more information, see about_Remote_Requirements.

 HOW DOES REMOTING WORK?

   When you submit a remote command, the command is transmitted across
   the network to the Windows PowerShell engine on the remote computer,
   and it runs in the Windows PowerShell client on the remote computer.
   The command results are sent back to the local computer and appear in
   the Windows PowerShell session on the local computer.

   To transmit the commands and receive the output, Windows PowerShell uses
   the WS-Management protocol. For information about the WS-Management
   protocol, see "WS-Management Protocol" in the MSDN (Microsoft Developer
   Network) library at http://go.microsoft.com/fwlink/?LinkId=144634.

 IS WINDOWS POWERSHELL REMOTING SECURE?

    When you connect to a remote computer, the system uses the user
    name and password credentials on the local computer or the credentials
    that you supply in the command to log you in to the remote computer.
    The credentials and the rest of the transmission are encrypted.

    To add additional protection, you can configure the remote computer
    to use Secure Sockets Layer (SSL) instead of HTTP to listen for
    Windows Remote Management (WinRM) requests. Then, users can use
    the UseSSL parameters of the Invoke-Command, New-PSSession, and
    Enter-PSSession cmdlets when establishing a connection. This option
    uses the more secure HTTPS channel instead of HTTP.

 DO ALL REMOTE COMMANDS REQUIRE WINDOWS POWERSHELL REMOTING?

   No. Several cmdlets have a ComputerName parameter that lets
   you get objects from the remote computer.

   These cmdlets do not use Windows PowerShell remoting. So, you
   can use them on any computer that is running Windows PowerShell,
   even if the computer is not configured for Windows PowerShell
   remoting or if the computer does not meet the requirements for
   Windows PowerShell remoting.

   These cmdlets include the following cmdlets:

       Get-Process
       Get-Service
       Get-WinEvent
       Get-EventLog
       Get-WmiObject
       Test-Connection

   To find all the cmdlets with a ComputerName parameter, type:

        get-help * -parameter ComputerName

   To determine whether the ComputerName parameter of a particular cmdlet
   requires Windows PowerShell remoting, see the parameter description. To
   display the parameter description, type:

    get-help <cmdlet-name> -parameter ComputerName

   For example:

        get-help get-process -parameter Computername

   For all other commands, use the Invoke-Command cmdlet.

 HOW DO I RUN A COMMAND ON A REMOTE COMPUTER?

   To run a command on a remote computer, use the Invoke-Command cmdlet.

   Enclose your command in braces ( {} ) to make it a script block. Use
   the ScriptBlock parameter of Invoke-Command to specify the command.

   You can use the ComputerName parameter of Invoke-Command to specify
   a remote computer. Or, you can create a persistent connection to a remote
   computer (a session) and then use the Session parameter of Invoke-Command
   to run the command in the session.

   For example, the following commands run a Get-Process command remotely.

      invoke-command -computername Server01, Server02 -scriptblock {get-process}

        - OR -

      invoke-command -session $s -scriptblock {get-process}

   To interrupt a remote command, type CTRL+C. The interruption request is
   passed to the remote computer, where it terminates the remote command.

   For more information about remote commands, see about_Remote and the Help
   topics for the cmdlets that support remoting.

 CAN I JUST "TELNET INTO" A REMOTE COMPUTER?

    You can use the Enter-PSSession cmdlet to start an interactive session
    with a remote computer.

    At the Windows Powershell prompt, type:

    Enter-PSSession <ComputerName>

    The command prompt changes to show that you are connected to the remote
    computer.

        <ComputerName>\C:>

    Now, the commands that you type run on the remote computer just as
    though you typed them directly on the remote computer.

    To end the interactive session, type:

        Exit-PSSession

    An interactive session is a persistent session that uses the WS-Management
    protocol. It is not the same as using Telnet, but it provides a similar
    experience.

    For more information, see Enter-PSSession.

 CAN I CREATE A PERSISTENT CONNECTION?

    Yes. You can run remote commands by specifying the name of the
    remote computer, its NetBIOS name, or its IP address. Or, you can run
    remote commands by specifying a Windows PowerShell session (PSSession)
    that is connected to the remote computer.

    When you use the ComputerName parameter of Invoke-Command or
    Enter-PSSession, Windows PowerShell establishes a temporary
    connection. Windows PowerShell uses the connection to run only the current
    command, and then it closes the connection. This is a very efficient
    method for running a single command or several unrelated commands, even
    on many remote computers.

    When you use the New-PSSession cmdlet to create a PSSession, Windows
    PowerShell establishes a persistent connection for the PSSession. Then,
    you can run multiple commands in the PSSession, including commands that
    share data.

    Typically, you create a PSSession to run a series of related commands
    that share data. Otherwise, the temporary connection created by the
    ComputerName parameter is sufficient for most commands.

    For more information about sessions, see about_PSSessions.

 CAN I RUN COMMANDS ON MORE THAN ONE COMPUTER AT A TIME?

   Yes. The ComputerName parameter of the Invoke-Command cmdlet accepts
   multiple computer names, and the Session parameter accepts
   multiple PSSessions.

   When you run an Invoke-Command command, Windows PowerShell runs the
   commands on all of the specified computers or in all of the specified
   PSSessions.

   Windows PowerShell can manage hundreds of concurrent remote connections.
   However, the number of remote commands that you can send might be limited
   by the resources of your computer and its capacity to establish and
   maintain multiple network connections.

   For more information, see the example in the Invoke-Command Help
   topic.

 WHERE ARE MY PROFILES?

    Windows PowerShell profiles are not run automatically in remote sessions,
    so the commands that the profile adds are not present in the session. In
    addition, the $profile automatic variable is not populated in remote
    sessions.

    To run a profile in a session, use the Invoke-Command cmdlet.

    For example, the following command runs the CurrentUserCurrentHost profile
    from the local computer in the session in $s.

        invoke-command -session $s -filepath $profile

    The following command runs the CurrentUserCurrentHost profile from
    the remote computer in the session in $s. Because the $profile variable
    is not populated, the command uses the explicit path to the profile.

        invoke-command -session $s {. "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"}

    After running this command, the commands that the profile adds to the session
    are available in $s.

    You can also use a startup script in a session configuration to run a
    profile in every remote session that uses the session configuration.

    For more information about Windows PowerShell profiles,
    see about_Profiles. For more information about session configurations,
    see Register-PSSessionConfiguration.

 HOW DOES THROTTLING WORK ON REMOTE COMMANDS?

   To help you manage the resources on your local computer, Windows
   PowerShell includes a per-command throttling feature that lets you
   limit the number of concurrent remote connections that are established
   for each command.

   The default is 32 concurrent connections, but you can use the
   ThrottleLimit parameters of the cmdlets to set a custom throttle limit
   for particular commands.

   When you use the throttling feature, remember that it is applied to each
   command, not to the entire session or to the computer. If you are running
   commands concurrently in several sessions or PSSessions, the number of
   concurrent connections is the sum of the concurrent connections in all
   the sessions.

   To find cmdlets with a ThrottleLimit parameter, type:

    get-help * -parameter ThrottleLimit

 ARE THERE SYSTEM-SPECIFIC DIFFERENCES IN REMOTING?

   When you run commands on multiple computers, be aware of the differences
   between the remote computers, such as differences in the operating systems,
   the file system structure, and the registry.

   When you connect to a remote computer that is running Windows Vista or
   Windows Server 2003, the default starting location is the home directory
   of the current user, which is stored in the %homepath% environment variable
   ($env:homepath) and the Windows PowerShell $home variable. In Windows Vista,
   the home directory is typically C:\Users\<UserName>. In Windows Server 2003,
   the home directory is typically C:\Documents and Settings\<UserName>.

   When you connect to a remote computer that is running Windows XP, the
   default starting location is the home directory of the default user, which is
   stored in the %homepath% environment variable ($env:homepath) for the default
   user. The home directory is typically C:\Documents and Setting\Default User.

 IS THE OUTPUT OF REMOTE COMMANDS DIFFERENT FROM LOCAL OUTPUT?

   When you use Windows PowerShell locally, you send and receive "live" .NET
   Framework objects; "live" objects are objects that are associated with
   actual programs or system components. When you invoke the methods or change
   the properties of live objects, the changes affect the actual program or
   component. And, when the properties of a program or component change,
   the properties of the object that represent them also change.

   However, because most live objects cannot be transmitted over the network,
   Windows PowerShell "serializes" most of the objects sent in remote commands,
   that is, it converts each object into a series of XML (Constraint Language
   in XML [CLiXML]) data elements for transmission.

   When Windows PowerShell receives a serialized object, it converts
   the XML into a deserialized object type. The deserialized object
   is an accurate record of the properties of the program or component at
   a previous time, but it is no longer "live", that is, it
   is no longer directly associated with the component. And, the methods are
   removed because they are no longer effective.

   Typically, you can use deserialized objects just as you would use live
   objects, but you must be aware of their limitations. Also, the objects
   that are returned by the Invoke-Command cmdlet have additional properties
   that help you to determine the origin of the command.

   Some object types, such as DirectoryInfo objects and GUIDs, are converted
   back into live objects when they are received. These objects do not need
   any special handling or formatting.

   For information about interpreting and formatting remote output, see
   about_Remote_Output.

 CAN I RUN BACKGROUND JOBS REMOTELY?

   Yes. A Windows PowerShell background job is a Windows PowerShell
   command that runs asynchronously without interacting with the session. When
   you start a background job, the command prompt returns immediately, and you
   can continue to work in the session while the job runs even if it runs for
   an extended period of time.

   You can start a background job even while other commands are running because
   background jobs always run asynchronously in a temporary session.

   You can run background jobs on a local or remote computer. By default, a
   background job runs on the local computer. However, you can use the AsJob
   parameter of the Invoke-Command cmdlet to run any remote command as a
   background job. And, you can use Invoke-Command to run a Start-Job
   command remotely.

   For more information about background jobs in Windows PowerShell,
   see about_Jobs and about_Remote_Jobs.

 CAN I RUN WINDOWS PROGRAMS ON A REMOTE COMPUTER?

    You can use Windows PowerShell remote commands to run Windows-based
    programs on remote computers. For example, you can run Shutdown.exe
    or Ipconfig on a remote computer.

    However, you cannot use Windows PowerShell commands to open the user
    interface for any program on a remote computer.

    When you start a Windows program on a remote computer, the command is
    not completed, and the Windows PowerShell command prompt does not return,
    until the program is finished or until you press CTRL+C to interrupt the
    command. For example, if you run the IpConfig program on a remote computer,
    the command prompt does not return until IpConfig is completed.

    If you use remote commands to start a program that has a user interface,
    the program process starts, but the user interface does not appear. The
    Windows PowerShell command is not completed, and the command prompt does
    not return until you stop the program process or until you press CTRL+C,
    which interrupts the command and stops the process.

    For example, if you use a Windows PowerShell command to run Notepad on a
    remote computer, the Notepad process starts on the remote computer, but
    the Notepad user interface does not appear. To interrupt the command and
    restore the command prompt, press CTRL+C.

 CAN I LIMIT THE COMMANDS THAT USERS CAN RUN REMOTELY ON MY COMPUTER?

    Yes. Every remote session must use one of the session configurations
    on the remote computer. You can manage the session configurations on
    your computer (and the permissions to those session configurations)
    to determine who can run commands remotely on your computer and which
    commands they can run.

    A session configuration configures the environment for the session.
    You can define the configuration by using an assembly that implements
    a new configuration class or by using a script that runs in the session.
    The configuration can determine the commands that are available in the
    session. And, the configuration can include settings that protect the
    computer, such as settings that limit the amount of data that the session
    can receive remotely in a single object or command. You can also specify
    a security descriptor that determines the permissions that are required
    to use the configuration.

    The Enable-PSRemoting cmdlet creates a default session configuration
    on your computer, Microsoft.PowerShell (and Microsoft.PowerShell32 on
    64-bit operating systems). Enable-PSRemoting sets the security descriptor
    for the configuration to allow only members of the Administrators group
    on your computer to use them.

    You can use the session configuration cmdlets to edit the default
    session configurations, to create new session configurations, and to change
    the security descriptors of all the session configurations.

    When users use the Invoke-Command, New-PSSession, or Enter-PSSession
    cmdlets, they can use the ConfigurationName parameter to indicate the
    session configuration that is used for the session. And, they can change
    the default configuration that their sessions use by changing the value
    of the $PSSessionConfigurationName preference variable in the session.

    For more information about session configurations, see the Help for
    the session configuration cmdlets. To find the session configuration
    cmdlets, type:

    get-command *pssessionconfiguration

 WHAT ARE FAN-IN AND FAN OUT CONFIGURATIONS?

   The most common Windows PowerShell remoting scenario involving
   multiple computers is the one-to-many configuration, in which one
   local computer (the administrator's computer) runs Windows PowerShell
   commands on numerous remote computers. This is known as the
   "fan-out" scenario.

   However, in some enterprises, the configuration is many-to-one, where
   many client computers connect to a single remote computer that is
   running Windows PowerShell, such as a file server or a kiosk.
   This is known as the "fan-in" configuration.

   Windows PowerShell remoting supports both fan-out and fan-in
   configurations.

   For the fan-out configuration, Windows PowerShell uses the Web Services for
   Management (WS-Management) protocol and the WinRM service that supports the
   Microsoft implementation of WS-Management. When a local computer connects to
   a remote computer, WS-Management establishes a connection and uses a plug-in
   for Windows PowerShell to start the Windows PowerShell host process
   (Wsmprovhost.exe) on the remote computer. The user can specify an alternate
   port, an alternate session configuration, and other features to customize
   the remote connection.

   To support the "fan-in" configuration, Windows PowerShell uses Internet
   Information Services (IIS) to host WS-Management, to load the Windows
   PowerShell plug-in, and to start Windows PowerShell. In this scenario,
   instead of starting each Windows PowerShell session in a separate process,
   all Windows PowerShell sessions run in the same host process.

   IIS hosting and fan-in remote management is not supported in Windows XP or
   in Windows Server 2003.

   In a fan-in configuration, the user can specify a connection URI and an
   HTTP endpoint, including the transport, computer name, port, and application
   name. IIS forwards all the requests with a specified application name to the
   application. The default is WS-Management, which can host Windows
   PowerShell.

   You can also specify an authentication mechanism and prohibit or allow
   redirection from HTTP and HTTPS endpoints.

 CAN I TEST REMOTING ON A SINGLE COMPUTER (NOT IN A DOMAIN)?

    Yes. Windows PowerShell remoting is available even when the local
    computer is not in a domain. You can use the remoting features to
    connect to sessions and to create sessions on the same computer. The
    features work the same as they do when you connect to a remote computer.

    To run remote commands on a computer in a workgroup, change the
    following Windows settings on the computer.

    Caution: These settings affect all users on the system and they can
             make the system more vulnerable to a malicious attack. Use
             caution when making these changes.

    --  Windows XP with SP2:

        Use Local Security Settings (Secpol.msc) to change the setting of the
        "Network Access: Sharing and security model for local accounts" policy
        in Security Settings\Local Policies\Security Options to "Classic".

    --  Windows Vista:

        Create the following registry entry, and then set its value to 1:
        LocalAccountTokenFilterPolicy in
        HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

        You can use the following Windows PowerShell command to add this entry:

        new-itemproperty `
        –path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System `
        –name LocalAccountTokenFilterPolicy –propertyType DWord –value 1

    --  Windows 2003:

        No changes are needed because the default setting of the
        "Network Access: Sharing and security model for local accounts" policy
        is "Classic". Verify the setting in case it has changed.

 CAN I RUN REMOTE COMMANDS ON A COMPUTER IN ANOTHER DOMAIN?

    Yes. Typically, the commands run without error, although you might need
    to use the Credential parameter of the Invoke-Command, New-PSSession,
    or Enter-PSSession cmdlets to provide the credentials of a member of the
    Administrators group on the remote computer. This is sometimes required
    even when the current user is a member of the Administrators group on the
    local and remote computers.

    However, if the remote computer is not in a domain that the local computer
    trusts, the remote computer might not be able to authenticate the user's
    credentials.

    To enable authentication, use the following command to add the remote
    computer to the list of trusted hosts for the local computer in WinRM.
    Type the command at the Windows PowerShell prompt.

        set-item WSMan:\localhost\Client\TrustedHosts -value <Remote-computer-name>

    For example, to add the Server01 computer to the list of trusted hosts
    on the local computer, type the following command at the Windows
    PowerShell prompt:

        set-item WSMan:\localhost\Client\TrustedHosts -value Server01

SEE ALSO
    about_Remote
    about_Profiles
    about_PSSessions
    about_Remote_Jobs
    Invoke-Command
    New-PSSession


about_Remote_Jobs

TOPIC
    about_Remote_Jobs

SHORT DESCRIPTION
    Describes how to run background jobs on remote computers.

DETAILED DESCRIPTION
    A background job is a command that runs asynchronously without interacting
    with the current session. The command prompt returns immediately, and you
    can continue to use the session while the job runs.

    By default, background jobs run on the local computer. However, you can
    use several different procedures to run background jobs on remote
    computers.

    This topic explains how to run a background job on a remote computer. For
    information about how to run background jobs on a local computer, see
    about_Jobs. For more information about background jobs, see
    about_Job_Details.

 REMOTE BACKGROUND JOBS

    You can run background jobs on remote computers by using three different
    methods.

    -- Start an interactive session with a remote computer, and start a job
       in the interactive session. The procedures are the same as running a
       local job, although all actions are performed on the remote computer.

    -- Run a background job on a remote computer that returns its results to
       the local computer. Use this method when you want to collect the
       results of background jobs and maintain them in a central location on
       the local computer.

    -- Run a background job on a remote computer that maintains its results
       on the remote computer. Use this method when the job data is more
       securely maintained on the originating computer.

 START A BACKGROUND JOB IN AN INTERACTIVE SESSION

    You can start an interactive session with a remote computer and then
    start a background job during the interactive session. For more
    information about interactive sessions, see about_Remote, and
    see Enter-PSSession.

    The procedure for starting a background job in an interactive session is
    almost identical to the procedure for starting a background job on the
    local computer. However, all of the operations occur on the remote
    computer, not the local computer.

    STEP 1: ENTER-PSSESSION

    Use the Enter-PSSession cmdlet to start an interactive session with a
    remote computer. You can use the ComputerName parameter of Enter-PSSession
    to establish a temporary connection for the interactive session. Or, you
    can use the Session parameter to run the interactive session in a Windows
    PowerShell session (PSSession).

    The following command starts an interactive session on the Server01
    computer.

        C:\PS> Enter-PSSession -computername Server01

    The command prompt changes to show that you are now connected to the
    Server01 computer.

        Server01\C:>

    STEP 2: START-JOB

    To start a background job in the session, use the Start-Job cmdlet.

    The following command runs a background job that gets the events in the
    Windows PowerShell event log on the Server01 computer. The Start-Job
    cmdlet returns an object that represents the job.

    This command saves the job object in the $job variable.

        Server01\C:> $job = start-job -scriptblock {get-eventlog "Windows PowerShell"}

    While the job runs, you can use the interactive session to run other
    commands, including other background jobs. However, you must keep the
    interactive session open until the job is completed. If you end the
    session, the job is interrupted, and the results are lost.

    STEP 3: GET-JOB

    To find out if the job is complete, display the value of the $job variable,
    or use the Get-Job cmdlet to get the job. The following command uses the
    Get-Job cmdlet to display the job.

        Server01\C:> get-job $job

        SessionId  Name  State      HasMoreData  Location   Command
        ---------  ----  -----      -----------  --------   -------
        1          Job1  Complete   True         localhost  get-eventlog "Windows PowerShell"

    The Get-Job output shows that job is running on the "localhost" computer
    because the job was started on and is running on the same computer (in
    this case, Server01).

    STEP 4: RECEIVE-JOB

    To get the results of the job, use the Receive-Job cmdlet. You can display
    the results in the interactive session or save them to a file on the remote
    computer. The following command gets the results of the job in the $job
    variable. The command uses the redirection operator (>) to save the results
    of the job in the PsLog.txt file on the Server01 computer.

        Server01\C:> receive-job $job > c:\logs\PsLog.txt

    STEP 5: EXIT-PSSESSION

    To end the interactive session, use the Exit-PSSession cmdlet. The command
    prompt changes to show that you are back in the original session on the
    local computer.

        Server01\C:> Exit-PSSession
        C:\PS>

    STEP 6: INVOKE-COMMAND: GET CONTENT

    To view the contents of the PsLog.txt file on the Server01 computer at any
    time, start another interactive session, or run a remote command. This type
    of command is best run in a PSSession (a persistent connection) in case you
    want to use several commands to investigate and manage the data in the
    PsLog.txt file. For more information about PSSessions,
    see about_PSSessions.

    The following commands use the New-PSSession cmdlet to create a PSSession
    that is connected to the Server01 computer, and they use the Invoke-Command
    cmdlet to run a Get-Content command in the PSSession to view the contents
    of the file.

        C:\PS> $s = new-pssession -computername Server01
        C:\PS> invoke-command -session $s -scriptblock {get-content c:\logs\pslog.txt}

 START A REMOTE JOB THAT RETURNS THE RESULTS TO THE LOCAL COMPUTER (ASJOB)

    To start a background job on a remote computer that returns the command
    results to the local computer, use the AsJob parameter of a cmdlet such
    as the Invoke-Command cmdlet.

    When you use the AsJob parameter, the job object is actually created on
    the local computer even though the job runs on the remote computer. When
    the job is completed, the results are returned to the local computer.

    You can use the cmdlets that contain the Job noun (the Job cmdlets) to
    manage any job created by any cmdlet. Many of the cmdlets that have
    AsJob parameters do not use Windows PowerShell remoting, so
    you can use them even on computers that are not configured for
    remoting and that do not meet the requirements for remoting.

    STEP 1: INVOKE-COMMAND -ASJOB

    The following command uses the AsJob parameter of Invoke-Command to start
    a background job on the Server01 computer. The job runs a Get-Eventlog
    command that gets the events in the System log. You can use the JobName
    parameter to assign a display name to the job.

       invoke-command -computername Server01 -scriptblock {get-eventlog system} -asjob

    The results of the command resemble the following sample output.

       SessionId   Name    State      HasMoreData     Location   Command
       ---------   ----    -----      -----------     --------   -------
       1           Job1    Running    True            Server01   get-eventlog system

    When the AsJob parameter is used, Invoke-Command returns the same type of
    job object that Start-Job returns. You can save the job object in a
    variable, or you can use a Get-Job command to get the job.

    Note that the value of the Location property shows that the job ran on the
    Server01 computer.

    STEP 2: GET-JOB

    To manage a job started by using the AsJob parameter of the Invoke-Command
    cmdlet, use the Job cmdlets. Because the job object that represents the
    remote job is on the local computer, you do not need to run remote commands
    to manage the job.

    To determine whether the job is complete, use a Get-Job command. The
    following command gets all of the jobs that were started in the current
    session.

        get-job

    Because the remote job was started in the current session, a local Get-Job
    command gets the job. The State property of the job object shows that the
    command was completed successfully.

       SessionId   Name   State      HasMoreData     Location   Command
       ---------   ----   -----      -----------     --------   -------
       1           Job1   Completed  True            Server01   get-eventlog system

    STEP 3: RECEIVE-JOB

    To get the results of the job, use the Receive-Job cmdlet. Because the job
    results are automatically returned to the computer where the job object
    resides, you can get the results with a local Receive-Job command.

    The following command uses the Receive-Job cmdlet to get the results of the
    job. It uses the session ID to identify the job. This command saves the job
    results in the $results variable. You can also redirect the results to a
    file.

       $results = receive-job -id 1

 START A REMOTE JOB THAT KEEPS THE RESULTS ON THE REMOTE COMPUTER

    To start a background job on a remote computer that keeps the command
    results on the remote computer, use the Invoke-Command cmdlet to run
    a Start-Job command on a remote computer. You can use this method to run
    background jobs on multiple computers.

    When you run a Start-Job command remotely, the job object is created on the
    remote computer, and the job results are maintained on the remote computer.
    From the perspective of the job, all operations are local. You are just
    running commands remotely to manage a local job on the remote computer.

    STEP 1: INVOKE-COMMAND START-JOB

    Use the Invoke-Command cmdlet to run a Start-Job command on a remote
    computer.

    This command requires a PSSession (a persistent connection). If you use
    the ComputerName parameter of Invoke-Command to establish a temporary
    connection, the Invoke-Command command is considered to be complete when
    the job object is returned. As a result, the temporary connection is
    closed, and the job is canceled.

    The following command uses the New-PSSession cmdlet to create a PSSession
    that is connected to the Server01 computer. The command saves the PSSession
    in the $s variable.

        $s = new-pssession -computername Server01

    The next command uses the Invoke-Command cmdlet to run a Start-Job command
    in the PSSession. The Start-Job command and the Get-Eventlog command are
    enclosed in braces.

       invoke-command -session $s -scriptblock {start-job -scriptblock {get-eventlog system}}

    The results resemble the following sample output.

       Id       Name    State      HasMoreData     Location   Command
       --       ----    -----      -----------     --------   -------
       2        Job2    Running    True            Localhost  get-eventlog system

    When you run a Start-Job command remotely, Invoke-Command returns the same
    type of job object that Start-Job returns. You can save the job object in
    a variable, or you can use a Get-Job command to get the job.

    Note that the value of the Location property shows that the job ran on the
    local computer, known as "LocalHost", even though the job ran on the
    Server01 computer. Because the job object is created on the Server01
    computer and the job runs on the same computer, it is considered to
    be a local background job.

    STEP 2: INVOKE-COMMAND GET-JOB

    To manage a remote background job, use the Job cmdlets. Because the job
    object is on the remote computer, you need to run remote commands to get,
    stop, wait for, or retrieve the job results.

    To see if the job is complete, use an Invoke-Command command to run a
    Get-Job command in the PSSession that is connected to the Server01
    computer.

        invoke-command -session $s -scriptblock {get-job}

    The command returns a job object. The State property of the job object
    shows that the command was completed successfully.

       SessionId       Name    State      HasMoreData     Location   Command
       ---------       ----    -----      -----------     --------   -------
       2               Job2    Completed  True            LocalHost   get-eventlog system

    STEP 3: INVOKE-COMMAND RECEIVE-JOB

    To get the results of the job, use the Invoke-Command cmdlet to run a
    Receive-Job command in the PSSession that is connected to the Server01
    computer.

    The following command uses the Receive-Job cmdlet to get the results of
    the job. It uses the session ID to identify the job. This command saves
    the job results in the $results variable. It uses the Keep parameter of
    Receive-Job to keep the result in the job cache on the remote
    computer.

        $results = invoke-command -session $s -scriptblock {receive-job -sessionid 2 -keep}

    You can also redirect the results to a file on the local or remote
    computer. The following command uses a redirection operator to save the
    results in a file on the Server01 computer.

        invoke-command -session $s -command {receive-job -sessionid 2 > c:\logs\pslog.txt}

SEE ALSO
    about_Jobs
    about_Job_Details
    about_Remote
    Invoke-Command
    Start-Job
    Get-Job
    Wait-Job
    Stop-Job
    Remove-Job
    New-PSSession
    Enter-PSSession
    Exit-PSSession


about_Remote_Output

TOPIC
    about_Remote_Output

SHORT DESCRIPTION
    Describes how to interpret and format the output of remote commands.

LONG DESCRIPTION
    The output of a command that was run on a remote computer might look
    like output of the same command run on a local computer, but there are
    some significant differences.

    This topic explains how to interpret, format, and display the output
    of commands that are run on remote computers.

 DISPLAYING THE COMPUTER NAME

    When you use the Invoke-Command cmdlet to run a command on a remote
    computer, the command returns an object that includes the name of
    the computer that generated the data. The remote computer name is
    stored in the PSComputerName property.

    For many commands, the PSComputerName is displayed by default. For
    example, the following command runs a Get-Culture command on two
    remote computers, Server01 and Server02. The output, which appears
    below, includes the names of the remote computers on which the command
    ran.

        C:\PS> invoke-command -script {get-culture} -comp Server01, Server02

        LCID  Name    DisplayName                PSComputerName
        ----  ----    -----------                --------------
        1033  en-US   English (United States)    Server01
        1033  es-AR   Spanish (Argentina)        Server02

    You can use the HideComputerName parameter of Invoke-Command to hide
    the PSComputerName property. This parameter is designed for commands
    that collect data from only one remote computer.

    The following command runs a Get-Culture command on the Server01
    remote computer. It uses the HideComputerName parameter to hide the
    PSComputerName property and related properties.

        C:\PS> invoke-command -scr {get-culture} -comp Server01 -HideComputerName

        LCID             Name             DisplayName
        ----             ----             -----------
        1033             en-US            English (United States)

     You can also display the PSComputerName property if it is not displayed
     by default.

     For example, the following commands use the Format-Table cmdlet to add
     the PSComputerName property to the output of a remote Get-Date command.

        C:\PS> $dates = invoke-command -script {get-date} -computername Server01, Server02
        C:\PS> $dates | format-table DateTime, PSComputerName -auto

        DateTime                            PSComputerName
        --------                            --------------
        Monday, July 21, 2008 7:16:58 PM    Server01
        Monday, July 21, 2008 7:16:58 PM    Server02

 DISPLAYING THE MACHINENAME PROPERTY

    Several cmdlets, including Get-Process, Get-Service, and Get-EventLog,
    have a ComputerName parameter that gets the objects on a remote computer.
    These cmdlets do not use Windows PowerShell remoting, so you can use them
    even on computers that are not configured for remoting in Windows
    PowerShell.

    The objects that these cmdlets return store the name of the remote computer
    in the MachineName property. (These objects do not have a PSComputerName
    property.)

    For example, this command gets the PowerShell process on the Server01 and
    Server02 remote computers. The default display does not include the
    MachineName property.

        C:\PS> get-process powershell -computername server01, server02

        Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
        -------  ------    -----      ----- -----   ------     -- -----------
            920      38    97524     114504   575     9.66   2648 powershell
            194       6    24256      32384   142            3020 powershell
            352      27    63472      63520   577     3.84   4796 powershell

    You can use the Format-Table cmdlet to display the MachineName property
    of the process objects.

    For example, the following command saves the processes in the $p variable
    and then uses a pipeline operator (|) to send the processes in $p to the
    Format-Table command. The command uses the Property parameter of
    Format-Table to include the MachineName property in the display.

        C:\PS> $p = get-process powershell -comp Server01, Server02
        C:\PS> $P | format-table -property ID, ProcessName, MachineName -auto

        Id ProcessName MachineName
        -- ----------- -----------
        2648 powershell  Server02
        3020 powershell  Server01
        4796 powershell  Server02

    The following more complex command adds the MachineName property to the
    default process display. It uses hash tables to specify calculated
    properties. Fortunately, you do not have to understand it to use it.

    (Note that the backtick [`] is the continuation character.)

        C:\PS> $p = get-process powershell -comp Server01, Server02

        C:\PS> $p | format-table -property Handles, `
                    @{Label="NPM(K)";Expression={[int]($_.NPM/1024)}}, `
                    @{Label="PM(K)";Expression={[int]($_.PM/1024)}}, `
                    @{Label="WS(K)";Expression={[int]($_.WS/1024)}}, `
                    @{Label="VM(M)";Expression={[int]($_.VM/1MB)}}, `
                    @{Label="CPU(s)";Expression={if ($_.CPU -ne $()){ $_.CPU.ToString("N")}}}, `
                    Id, ProcessName, MachineName -auto

        Handles NPM(K) PM(K)  WS(K) VM(M) CPU(s)   Id ProcessName MachineName
        ------- ------ -----  ----- ----- ------   -- ----------- -----------
            920     38 97560 114532   576        2648 powershell  Server02
            192      6 24132  32028   140        3020 powershell  Server01
            438     26 48436  59132   565        4796 powershell  Server02

 DESERIALIZED OBJECTS
    When you run remote commands that generate output, the command output is
    transmitted across the network back to the local computer.

    Because most live Microsoft .NET Framework objects (such as the objects
    that Windows PowerShell cmdlets return) cannot be transmitted over the
    network, the live objects are "serialized". In other words, the live
    objects are converted into XML representations of the object and its
    properties. Then, the XML-based serialized object is transmitted across
    the network.

    On the local computer, Windows PowerShell receives the XML-based serialized
    object and "deserializes" it by converting the XML-based object into a
    standard .NET Framework object.

    However, the deserialized object is not a live object. It is a snapshot of
    the object at the time that it was serialized, and it includes properties
    but no methods. You can use and manage these objects in Windows PowerShell,
    including passing them in pipelines, displaying selected properties, and
    formatting them.

    Most deserialized objects are automatically formatted for display by
    entries in the Types.ps1xml or Format.ps1xml files. However, the local
    computer might not have formatting files for all of the deserialized
    objects that were generated on a remote computer. When objects are
    not formatted, all of the properties of each object appear in the console
    in a streaming list.

    When objects are not formatted automatically, you can use the formatting
    cmdlets, such as Format-Table or Format-List, to format and display
    selected properties. Or, you can use the Out-GridView cmdlet to display
    the objects in a table.

    Also, if you run a command on a remote computer that uses cmdlets that you
    do not have on your local computer, the objects that the command returns
    might not be formatted properly because you do not have the formatting
    files for those objects on your computer. To get formatting data from
    another computer, use the Get-FormatData and Export-FormatData cmdlets.

    Some object types, such as DirectoryInfo objects and GUIDs, are converted
    back into live objects when they are received. These objects do not need
    any special handling or formatting.

 ORDERING THE RESULTS
    The order of the computer names in the ComputerName parameter of cmdlets
    determines the order in which Windows PowerShell connects to the remote
    computers. However, the results appear in the order in which the local
    computer receives them, which might be a different order.

    To change the order of the results, use the Sort-Object cmdlet. You can
    sort on the PSComputerName or MachineName property. You can also sort on
    another property of the object so that the results from different
    computers are interspersed.

SEE ALSO
    about_Remote
    Format-Table
    Get-EventLog
    Get-Process
    Get-Service
    Get-WmiObject
    Invoke-Command
    Out-GridView
    Select-Object


about_Remote_Requirements

TOPIC
    about_Remote_Requirements

SHORT DESCRIPTION
    Describes the system requirements and configuration requirements for
    running remote commands in Windows PowerShell.

LONG DESCRIPTION
    This topic describes the system requirements, user requirements, and
    resource requirements for establishing remote connections and running
    remote commands in Windows PowerShell. It also provides instructions for
    configuring remote operations.

    Note: Many cmdlets (including the Get-Service, Get-Process, Get-WMIObject,
          Get-EventLog, and Get-WinEvent cmdlets) get objects from remote
          computers by using Microsoft .NET Framework methods to retrieve the
          objects. They do not use the Windows PowerShell remoting
          infrastructure. The requirements in this document do not apply to
          these cmdlets.

          To find the cmdlets that have a ComputerName parameter but do not use
          Windows PowerShell remoting, read the description of the ComputerName
          parameter of the cmdlets.

 SYSTEM REQUIREMENTS

    The local and remote computers must have:

        --  Windows PowerShell 2.0 or later

        --  The Microsoft .NET Framework 2.0 or later

        --  Windows Remote Management 2.0

    To find the version number of an installed version of Windows PowerShell,
    use the $PSVersionTable automatic variable. The value of the
    $PSVersionTable.Version.Major property must be at least 2.

    Windows Remote Management 2.0 is included in Windows 7 and in
    Windows Server 2008 R2. It is also included in the integrated installation
    package for earlier versions of Windows that includes Windows PowerShell.

    Windows PowerShell Integrated Scripting Environment (ISE) and the
    Out-Gridview cmdlet require the Microsoft .NET Framework 3.5 with Service
    Pack 1. The Get-WinEvent cmdlet requires the Microsoft .NET Framework 3.5
    or greater. These upgrades are not required for remoting.

 USER PERMISSIONS

    To establish a remote connection and run remote commands, the current user
    must be a member of the Administrators group on the remote computer. Or,
    the current user must be able to provide the credentials of an
    administrator.

 RUN AS ADMINISTRATOR

    In Windows Vista, Windows Server 2008, and later versions of Windows,
    Administrator privileges are required for the following remoting
    operations:

        -- Establishing a remote connection to the local computer. This is
           commonly known as a "loopback" scenario.

        -- Managing session configurations on the local computer.

        -- Viewing and changing WS-Management settings on the local computer.
           These are the settings in the LocalHost node of the WSMAN: drive.

    To perform these tasks, you must start Windows PowerShell with the "Run
    as administrator" option even if you are a member of the Administrators
    group on the local computer.

    In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell
    with the "Run as administrator" option:

        1. Click Start, click All Programs, click Accessories, and then click
           the Windows PowerShell folder.

        2. Right-click Windows PowerShell, and then click
           "Run as administrator".

    In Windows Vista and Windows Server 2008, to start Windows PowerShell with
    the "Run as administrator" option:

        1. Click Start, click All Programs, and then click the Windows
           PowerShell folder.

        2. Right-click Windows PowerShell, and then click
           "Run as administrator".

    The "Run as administrator" option is also available in other Windows
    Explorer entries for Windows PowerShell, including shortcuts. Just
    right-click the item, and then click "Run as administrator".

    When you start Windows PowerShell from another program such as Cmd.exe, use
    the "Run as administrator" option to start the program.

 HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING

    The remoting features of Windows PowerShell are supported by the WinRM
    service, which is the Microsoft implementation of the Web Services for
    Management (WS-Management) protocol. To use the remoting features, you
    need to change the default configuration of WS-Management on the system.

    To configure Windows PowerShell to receive remote commands:

        1. Start Windows PowerShell. In Windows Vista and later versions of
           Windows, start Windows PowerShell with the "Run as administrator"
           option.

    2. At the command prompt, type:

       enable-psremoting

    This procedure allows users on other computers to establish remote
    connections and to run remote commands on the local computer. It also
    allows you to create a "loopback" connection on the local computer.

    To verify that remoting is configured correctly, run a test command such as
    the following command, which creates a remote session on the local
    computer.

          new-pssession

    If remoting is configured correctly, the command will create a session on
    the local computer and return an object that represents the session. The
    output should resemble the following sample output:

          C:\PS> new-pssession

          Id Name        ComputerName    State    ConfigurationName
          -- ----        ------------    -----    -----
          1  Session1    localhost       Opened   Microsoft.PowerShell

    If the command fails, see about_Remote_Troubleshooting for assistance.

 UNDERSTAND POLICIES

    When you work remotely, you use two instances of Windows PowerShell, one
    on the local computer and one on the remote computer. As a result, your
    work is affected by the Windows policies and the Windows PowerShell
    policies on the local and remote computers.

    In general, before you connect and as you are establishing the connection,
    the policies on the local computer are in effect. When you are using the
    connection, the policies on the remote computer are in effect.

SEE ALSO
    about_Remote
    about_PSSessions
    Invoke-Command
    Enter-PSSession
    New-PSSession


about_Remote_Troubleshooting

TOPIC
    about_Remote_Troubleshooting

SHORT DESCRIPTION
    Describes how to troubleshoot remote operations in Windows PowerShell.

LONG DESCRIPTION
    This section describes some of the problems that you might encounter when
    using the remoting features of Windows PowerShell that are based on
    WS-Management technology and it suggests solutions to these problems.

    Before using Windows PowerShell remoting, see about_Remote and
    about_Remote_Requirements for guidance on configuration and basic use Also,
    the Help topics for each of the remoting cmdlets, particularly the parameter
    descriptions, have useful information that is designed to help you avoid
    problems.

    Updated versions of this topic, and other Windows PowerShell help topics,
    can be found online in the Microsoft TechNet Library. To see the online
    version of this help topic, paste the following URL in your Internet
    browser:

    http://go.microsoft.com/fwlink/?LinkID=135188

    NOTE: On Windows Vista, Windows Server 2008, and later versions of Windows,
    to view or change settings for the local computer in the WSMan: drive,
    including changes to the session configurations, trusted hosts, ports, or
    listeners, start Windows PowerShell with the "Run as administrator" option.

 TROUBLESHOOTING PERMISSION AND AUTHENTICATION ISSUES

    This section discusses remoting problems that are related to user and
    computer permissions and remoting requirements.

    HOW TO RUN AS ADMINISTRATOR
    ---------------------------
        ERROR: Access is denied. You need to run this cmdlet from an elevated
        process.

    To start a remote session on the local computer, or to view or change
    settings for the local computer in the WSMan: drive, including changes
    to the session configurations, trusted hosts, ports, or listeners,
    start Windows PowerShell with the "Run as administrator" option.

    To start Windows PowerShell with the "Run as administrator option:

    -- Right-click a Windows PowerShell (or Windows PowerShell ISE) icon
       and then click "Run as administrator.

    To start Windows PowerShell with the "Run as administrator option in
    Windows 7 and Windows Server 2008 R2.

    -- In the Windows taskbar, right-click the Windows PowerShell icon,
       and then click "Run Windows PowerShell as admin."

    Note: In Windows Server 2008 R2, the Windows PowerShell icon is pinned
    to the taskbar by default.

    HOW TO ENABLE REMOTING
    ----------------------
        ERROR:  ACCESS IS DENIED
        - or -
        ERROR: The connection to the remote host was refused. Verify that the
        WS-Management service is running on the remote host and configured to
        listen for requests on the correct port and HTTP URL.

    No configuration is required to enable a computer to send remote
    commands. However, to receive remote commands, the computer must be
    configured for remoting. The configuration includes starting the WinRM
    service, setting the startup type for the WinRM service to Automatic,
    creating listeners for HTTP and HTTPS connections, and creating default
    session configurations.

    To configure a computer to receive remote commands, use the
    Enable-PSRemoting cmdlet. The following command enables all required
    remote settings, enables the session configurations, and restarts the
    WinRM service to make the changes effective.

        enable-psremoting

    To suppress all user prompts, type:

        enable-psremoting -force

    For more information, see Enable-PSRemoting.

    HOW TO ENABLE REMOTING IN AN ENTERPRISE
    ---------------------------------------
        ERROR:  ACCESS IS DENIED
        - or -
        ERROR: The connection to the remote host was refused. Verify that the
        WS-Management service is running on the remote host and configured to
        listen for requests on the correct port and HTTP URL.

    To enable a single computer to receive remote Windows PowerShell commands
    and accept connections, use the Enable-PSRemoting cmdlets.

    To enable remoting for multiple computers in an enterprise, you can use the
    following scaled options.

    -- To configure listeners for remoting, enable the "Allow automatic
       configuration of listeners" group policy. For instructions, see
       "How to Enable Listeners by Using a Group Policy" (below).

    -- To set the startup type of the Windows Remote Management (WinRM)
       to Automatic on multiple computers, use the Set-Service cmdlet. For
       instructions, see "How to Set the Startup Type of the WinrM Service"
       (below).

    -- To enable a firewall exception, use the "Windows Firewall: Allow Local
       Port Exceptions" group policy. For instructions, see "How to Create a
       Firewall Exception by Using a Group Policy" (below).

    HOW TO ENABLE LISTENERS BY USING A GROUP POLICY
    ------------------------------------------------
        ERROR:  ACCESS IS DENIED
        - or -
        ERROR: The connection to the remote host was refused. Verify that the
        WS-Management service is running on the remote host and configured to
        listen for requests on the correct port and HTTP URL.

    To configure the listeners for all computers in a domain, enable the "Allow
    automatic configuration of listeners"  policy in the following Group Policy
    path:

        Computer Configuration\Administrative Templates\Windows Components
          \Windows Remote Management (WinRM)\WinRM service

    Enable the policy and specify the IPv4 and IPv6 filters. Wildcards (*) are
    permitted.

    HOW TO ENABLE A FIREWALL EXCEPTION BY USING A GROUP POLICY
    ----------------------------------------------------------
        ERROR:  ACCESS IS DENIED
        - or -
        ERROR: The connection to the remote host was refused. Verify that the
        WS-Management service is running on the remote host and configured to
        listen for requests on the correct port and HTTP URL.

    To enable a firewall exception for in all computers in a domain, enable the
    "Windows Firewall: Allow local port exceptions" policy in the following
    Group Policy path:

        Computer Configuration\Administrative Templates\Network
          \Network Connections\Windows Firewall\Domain Profile

    This policy allows members of the Administrators group on the computer to
    use Windows Firewall in Control Panel to create a firewall exception for
    the Windows Remote Management service.

    HOW TO SET THE STARTUP TYPE OF THE WINRM SERVICE
    ------------------------------------------------
        ERROR:  ACCESS IS DENIED

    Windows PowerShell remoting depends upon the Windows Remote Management
    (WinRM) service. The service must be running to support remote commands.

    On Windows Server 2003, Windows Server 2008, and Windows Server 2008 R2,
    the startup type of the Windows Remote Management (WinRM) service is
    Automatic.

    However, on Windows XP, Windows Vista, and Windows 7, the WinRM service is
    disabled by default.

    To set the startup type of a service on a remote computer, use the
    Set-Service cmdlet.

    To run the command on multiple computers, you can create a text file or
    CSV file of the computer names.

    For example, the following commands get a list of computer names from the
    Servers.txt file and then sets the startup type of the WinRM service on all
    of the computers to Automatic.

        C:\PS> $servers = get-content servers.txt

        C:\PS> set-service WinRM -computername $servers -startuptype Automatic

    To see the results use the Get-WMIObject cmdlet with the Win32_Service object.
    For more information, see Set-Service.

    HOW TO RECREATE THE DEFAULT SESSION CONFIGURATIONS
    --------------------------------------------------
        ERROR:  ACCESS IS DENIED

    To connect to the local computer and run commands remotely, the local
    computer must include session configurations for remote commands.

    When you use Enable-PSRemoting, it creates default session configurations
    on the local computer. Remote users use these session configurations
    whenever a remote command does not include the ConfigurationName parameter.

    If the default configurations on a computer are unregistered or deleted,
    use the Enable-PSRemoting cmdlet to recreate them. You can use this cmdlet
    repeatedly. It does not generate errors if a feature is already configured.

    If you change the default session configurations and want to restore the
    original default session configurations, use the
    Unregister-PSSessionConfiguration cmdlet to delete the changed session
    configurations and then use the Enable-PSRemoting cmdlet to restore them.
    Enable-PSRemoting does not change existing session configurations.

    Note: When Enable-PSRemoting restores the default session configuration, it
    does not create explicit security descriptors for the configurations.
    Instead, the configurations inherit the security descriptor of the RootSDDL,
    which is secure by default.

    To see the RootSDDL security descriptor, type:

        get-item wsman:\localhost\Service\RootSDDL

    To change the RootSDDL, use the Set-Item cmdlet in the WSMan: drive. To
    change the security descriptor of a session configuration, use the
    Set-PSSessionConfiguration cmdlet with the SecurityDescriptorSDDL or
    ShowSecurityDescriptorUI parameters.

    For more information about the WSMan: drive, see the Help topic for the
    WS-Management provider ("get-help wsman").

    HOW TO PROVIDE ADMINISTRATOR CREDENTIALS
    ----------------------------------------
        ERROR:  ACCESS IS DENIED

    To create a PSSession or run commands on a remote computer, by default, the
    current user must be a member of the Administrators group on the remote
    computer. Credentials are sometimes required even when the current user is
    logged on to an account that is a member of the Administrators group.

    If the current user is a member of the Administrators group on the remote
    computer, or can provide the credentials of a member of the Administrators
    group, use the Credential parameter of the New-PSSession, Enter-PSSession
    or Invoke-Command cmdlets to connect remotely.

    For example, the following command provides the credentials of an
    Administrator.

        Invoke-Command -ComputerName Server01 -Credential Domain01\Admin01

    For more information about the Credential parameter, see New-PSSession,
    Enter-PSSession or Invoke-Command.

    HOW TO ENABLE REMOTING FOR NON-ADMINISTRATIVE USERS
    ---------------------------------------------------
        ERROR:  ACCESS IS DENIED

    To establish a PSSession or run a command on a remote computer, the user
    must have permission to use the session configurations on the remote
    computer.

    By default, only members of the Administrators group on a computer have
    permission to use the default session configurations. Therefore, only
    members of the Administrators group can connect to the computer remotely.

    To allow other users to connect to the local computer, give the user
    Execute permissions to the default session configurations on the local
    computer.

    The following command opens a property sheet that lets you change the
    security descriptor of the default Microsoft.PowerShell session
    configuration on the local computer.

        Set-PSSessionConfiguration Microsoft.Powershell -ShowSecurityDescriptorUI

    For more information, see about_Session_Configurations.

    HOW TO ENABLE REMOTING FOR ADMINISTRATORS IN OTHER DOMAINS
    ----------------------------------------------------------
        ERROR:  ACCESS IS DENIED

    When a user in another domain is a member of the Administrators group on
    the local computer, the user cannot connect to the local computer remotely
    with Administrator privileges. By default, remote connections from other
    domains run with only standard user privilege tokens.

    However, you can use the LocalAccountTokenFilterPolicy registry entry to
    change the default behavior and allow remote users who are members of the
    Administrators group to run with Administrator privileges.

    Caution: The LocalAccountTokenFilterPolicy entry disables user account
             control (UAC) remote restrictions for all users of all affected
             computers. Consider the implications of this setting carefully
             before changing the policy.

    To change the policy, use the following command to set the value of the
    LocalAccountTokenFilterPolicy registry entry to 1.

        C:\PS> new-itemproperty -name LocalAccountTokenFilterPolicy -path `
            HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -propertyType `
            DWord -value 1

    HOW TO USE AN IP ADDRESS IN A REMOTE COMMAND
    -----------------------------------------------------
        ERROR:  The WinRM client cannot process the request. If the
        authentication scheme is different from Kerberos, or if the client
        computer is not joined to a domain, then HTTPS transport must be used
        or the destination machine must be added to the TrustedHosts
        configuration setting.

    The ComputerName parameters of the New-PSSession, Enter-PSSession and
    Invoke-Command cmdlets accept an IP address as a valid value. However,
    because Kerberos authentication does not support IP addresses, NTLM
    authentication is used by default whenever you specify an IP address.

    When using NTLM authentication, the following procedure is required
    for remoting.

    1. Configure the computer for HTTPS transport or add the IP addresses
       of the remote computers to the TrustedHosts list on the local
       computer.

       For instructions, see "How to Add a Computer to the TrustedHosts
       List" below.

    2. Use the Credential parameter in all remote commands.

       This is required even when you are submitting the credentials
       of the current user.

    HOW TO CONNECT REMOTELY FROM A WORKGROUP-BASED COMPUTER
    -------------------------------------------------------
        ERROR:  The WinRM client cannot process the request. If the
        authentication scheme is different from Kerberos, or if the client
        computer is not joined to a domain, then HTTPS transport must be used
        or the destination machine must be added to the TrustedHosts
        configuration setting.

    When the local computer is not in a domain, the following procedure is required
    for remoting.

    1. Configure the computer for HTTPS transport or add the names of the
       remote computers to the TrustedHosts list on the local computer.

       For instructions, see "How to Add a Computer to the TrustedHosts
       List" below.

    2. Verify that a password is set on the workgroup-based computer. If a
       password is not set or the password value is empty, you cannot run
       remote commands.

       To set password for your user account, use User Accounts in Control
       Panel.

    3. Use the Credential parameter in all remote commands.

       This is required even when you are submitting the credentials
       of the current user.

    HOW TO ADD A COMPUTER TO THE TRUSTED HOSTS LIST
    -----------------------------------------------

    The TrustedHosts item can contain a comma-separated list of computer
    names, IP addresses, and fully-qualified domain names. Wildcards
    are permitted.

    To view or change the trusted host list, use the WSMan: drive. The
    TrustedHost item is in the WSMan:\localhost\Client node.

    Only members of the Administrators group on the computer have permission
    to change the list of trusted hosts on the computer.

    Caution: The value that you set for the TrustedHosts item affects all
             users of the computer.

    To view the list of trusted hosts, use the following command:

        get-item wsman:\localhost\Client\TrustedHosts

    You can also use the Set-Location cmdlet (alias = cd) to navigate
    though the WSMan: drive to the location.
    For example: "cd WSMan:\localhost\Client; dir".

    To add all computers to the list of trusted hosts, use the following
    command, which places a value of * (all) in the ComputerName

        set-item wsman:localhost\client\trustedhosts -value *

    You can also use a wildcard character (*) to add all computers in a
    particular domain to the list of trusted hosts. For example, the following
    command adds all of the computers in the Fabrikam domain to the list of
    trusted hosts.

        set-item wsman:localhost\client\trustedhosts *.fabrikam.com

    To add the names of particular computers to the list of trusted hosts, use
    the following command format:

        set-item wsman:\localhost\Client\TrustedHosts -value <ComputerName>[,<ComputerName>]

    where each value <ComputerName> must have the following format:

        <Computer>.<Domain>.<Company>.<top-level-domain>

    For example:

        set-item wsman:\localhost\Client\TrustedHosts -value Server01.Domain01.Fabrikam.com

    To add a computer name to an existing list of trusted hosts, first save
    the current value in a variable, and then set the value to a
    comma-separated list that includes the current and new values.

    For example, to add the Server01 computer to an existing list of trusted
    hosts, use the following command

        $curValue = (get-item wsman:\localhost\Client\TrustedHosts).value

        set-item wsman:\localhost\Client\TrustedHosts -value "$curValue, Server01.Domain01.Fabrikam.com"

    To add the IP addresses of particular computers to the list of trusted hosts,
    use the following command format:

        set-item wsman:\localhost\Client\TrustedHosts -value <IP Address>

    For example:

        set-item wsman:\localhost\Client\TrustedHosts -value 172.16.0.0

    To add a computer to the TrustedHosts list of a remote computer, use the
    Connect-WSMan cmdlet to add a node for the remote computer to the WSMan: drive
    on the local computer. Then use a Set-Item command to add the computer.

    For more information about the Connect-WSMan cmdlet, see Connect-WSMan.

 TROUBLESHOOTING COMPUTER CONFIGURATION ISSUES
    This section discusses remoting problems that are related to particular
    configurations of a computer, domain, or enterprise.

    HOW TO CONFIGURE REMOTING ON ALTERNATE PORTS
    --------------------------------------------
        ERROR:  The connection to the specified remote host was refused. Verify
        that the WS-Management service is running on the remote host and
        configured to listen for requests on the correct port and HTTP URL.

    Windows PowerShell remoting uses port 80 for HTTP transport by default. The
    default port is used whenever the user does not specify the ConnectionURI
    or Port parameters in a remote command.

    To change the default port that Windows PowerShell uses, use Set-Item cmdlet
    in the WSMan: drive to change the Port value in the  listener leaf node.

    For example, the following command changes the default port to 8080.

        set-item wsman:\localhost\listener\listener*\port -value 8080

    HOW TO CONFIGURE REMOTING WITH A PROXY SERVER
    ---------------------------------------------
        ERROR: The client cannot connect to the destination specified in the
        request. Verify that the service on the destination is running and is
        accepting requests.

    Because Windows PowerShell remoting uses the HTTP protocol, it is affected
    by HTTP proxy settings. In enterprises that have proxy servers, users
    cannot access a Windows PowerShell remote computer directly.

    To resolve this problem, use proxy setting options in your remote command.
    The following settings are available:

        --  ProxyAccessType
        --  ProxyAuthentication
        --  ProxyCredential

    To set these options for a particular command, use the following procedure:

        1. Use the ProxyAccessType, ProxyAuthentication, and ProxyCredential
           parameters of the New-PSSessionOption cmdlet to create a session
           option object with the proxy settings for your enterprise. Save the
           option object is a variable.

        2. Use the variable that contains the option object as the value of the
           SessionOption parameter of a New-PSSession, Enter-PSSession, or
           Invoke-Command command.

    For example, the following command creates a session option object with
    proxy session options and then uses the object to create a remote session.

        C:\PS> $SessionOption = New-PSSessionOption -ProxyAccessType IEConfig `
                -ProxyAuthentication Negotiate -ProxyCredential Domain01\User01

        C:\PS> New-PSSession -ConnectionURI https://www.fabrikam.com

    For more information about the New-PSSessionOption cmdlet, see
    New-PSSessionOption.

    To set these options for all remote commands in the current session, use
    the option object that New-PSSessionOption creates in the value of the
    $PSSessionOption preference variable. For more information about the
    $PSSessionOption preference variable, see about_Preference_Variables.

    To set these options for all remote commands all Windows PowerShell sessions
    on the local computer, add the $PSSessionOption preference variable to your
    Windows PowerShell profile. For more information about Windows PowerShell
    profiles, see about_Profiles.

    HOW TO DETECT A 32-BIT SESSION ON A 64-BIT COMPUTER
    ---------------------------------------------------
        ERROR: The term "<tool-name>" is not recognized as the name of a cmdlet,
        function, script file, or operable program. Check the spelling of the
        name, or if a path was included, verify that the path is correct and try
        again.

    If the remote computer is running a 64-bit version of Windows, and the
    remote command is using a 32-bit session configuration, such as
    Microsoft.PowerShell32, Windows Remote Management (WinRM) loads a WOW64
    process and Windows automatically redirects all references to the
    %Windir%\System32 directory to the %windir%\SysWOW64 directory.

    As a result, if you try to use tools in the System32 directory that do
    not have counterparts in the SysWow64 directory, such as Defrag.exe,
    the tools cannot be found in the directory.

    To find the processor architecture that is being used in the session,
    use the value of the PROCESSOR_ARCHITECTURE environment variable. The
    following command finds the processor architecture of the session in the
    $s variable.

        C:\PS> $s = new-pssession -computername Server01 -configurationName CustomShell

        C:\PS> invoke-command -session $s {$env:PROCESSOR_ARCHITECTURE}
        x86

    For more information about session configurations, see
    about_session_configurations.

 TROUBLESHOOTING POLICY AND PREFERENCE ISSUES
    This section discusses remoting problems that are related to policies and
    preferences set on the local and remote computers.

    HOW TO CHANGE THE EXECUTION POLICY FOR IMPORT-PSSESSION AND IMPORT-MODULE
    -------------------------------------------------------------------------
        ERROR: Import-Module: File <filename> cannot be loaded because the
        execution of scripts is disabled on this system.

    The Import-PSSession and Export-PSSession cmdlets create modules that
    contains unsigned script files and formatting files.

    To import the modules that are created by these cmdlets, either by using
    Import-PSSession or Import-Module, the execution policy in the current
    session cannot be Restricted or AllSigned. (For information about Windows
    PowerShell execution policies, see about_Execution_Policies.

    To import the modules without changing the execution policy for the local
    computer that is set in the registry, use the Scope parameter of
    Set-ExecutionPolicy to set a less restrictive execution policy for a single
    process.

    For example, the following command starts a process with the RemoteSigned
    execution policy. The execution policy change affects only the current
    process and does not change the Windows PowerShell ExecutionPolicy registry
    setting.

        set-executionpolicy -scope process -executionpolicy RemoteSigned

    You can also use the ExecutionPolicy parameter of PowerShell.exe to start
    a single session with a less restrictive execution policy.

        powershell.exe -executionpolicy RemoteSigned

    For more information about the cmdlets, see Import-PSSession,
    Export-PSSession, and Import-Module. For more information about
    execution policies, see about_Execution_Policies. For more information
    about the PowerShell.exe console help options, type "powershell.exe -?".

    HOW TO SET AND CHANGE QUOTAS
    ----------------------------
        ERROR: The total data received from the remote client exceeded allowed
        maximum.

    You can use quotas to protect the local computer and the remote computer
    from excessive resource use, both accidental and malicious.

    The following quotas are available in the basic configuration.

    -- The WS-Management provider (WSMan:) provides several quota settings,
       such as the MaxEnvelopeSizeKB and MaxProviderRequests settings in the
       WSMan:\<ComputerName> node and the MaxConcurrentOperations,
       MaxConcurrentOperationsPerUser, and MaxConnections settings in the
       WSMan:\<ComputerName>\Service node.

    -- You can protect the local computer by using the
       MaximumReceivedDataSizePerCommandMB and MaximumReceivedObjectSizeMB
       parameters of the New-PSSessionOption cmdlet and the $PSSessionOption
       preference variable.

    -- You can protect the remote computer by adding restrictions to the session
       configurations, such as by using the MaximumReceivedDataSizePerCommandMB
       and MaximumReceivedObjectSizeMB parameters of the
       Register-PSSessionConfiguration cmdlet.

    When quotas conflict with a command, Windows PowerShell generates an error.

    To resolve the error, change the remote command to comply with the quota.
    Or, determine the source of the quota, and then increase the quota to allow
    the command to complete.

    For example, the following command increases the object size quota in the
    Microsoft.PowerShell session configuration on the remote computer from 10 MB
    (the default value) to 11 MB.

        Set-PSSessionConfiguration -name microsoft.powershell `
            -MaximumReceivedObjectSizeMB 11 -Force

    For more information about the New-PSSsessionOption cmdlet, see
    New-PSSessionOption.

    For more information about the WS-Management quotas, see the Help topic for
    the WS-Management provider (type "get-help WSMan").

    HOW TO RESOLVE TIMEOUT ERRORS
    -----------------------------
        ERROR: The WS-Management service cannot complete the operation within
        the time specified in OperationTimeout.

    You can use timeouts to protect the local computer and the remote computer
    from excessive resource use, both accidental and malicious. When timeouts
    are set on both the local and remote computer, Windows PowerShell uses the
    shortest timeout settings.

    The following timeouts are available in the basic configuration.

    -- The WS-Management provider (WSMan:) provides several client-side and
       service-side timeout settings, such as the MaxTimeoutms setting in the
       WSMan:\<ComputerName> node and the EnumerationTimeoutms and
       MaxPacketRetrievalTimeSeconds settings in the
       WSMan:\<ComputerName>\Service node.

    -- You can protect the local computer by using the CancelTimeout, IdleTimeout,
       OpenTimeout, and OperationTimeout parameters of the New-PSSessionOption
       cmdlet and the $PSSessionOption preference variable.

    -- You can also protect the remote computer by setting timeout values
       programmatically in the session configuration for the session.

    When a timeout value does not permit a operation to complete, Windows
    PowerShell terminates the operation and generates an error.

    To resolve the error, change the command to complete within the timeout
    interval or determine the source of the timeout limit and increase the
    timeout interval to allow the command to complete.

    For example, the following commans use the New-PSSessionOption cmdlet to
    create a session option object with an OperationTimeout value of 4 minutes
    (in MS) and then use the session option object to create a remote session.

        C:\PS> $pso = new-pssessionoption -operationtimeout 240000

        C:\PS> new-pssession -computername Server01 -sessionOption $pso

    For more information about the WS-Management timeouts, see the Help topic for
    the WS-Management provider (type "get-help WSMan").

    For more information about the New-PSSsessionOption cmdlet, see
    New-PSSessionOption.

 TROUBLESHOOTING UNRESPONSIVE BEHAVIOR

 This section discusses remoting problems that prevent a command from completing
 and prevent or delay the return of the Windows PowerShell prompt.

    HOW TO INTERRUPT A COMMAND
    --------------------------
    Some native Windows programs, such as programs with a user interface, console
    applications that prompt for input, and console applications that use the
    Win32 console API, do not work correctly in the Windows PowerShell remote host.

    When you use these programs, you might see unexpected behavior, such as no
    output, partial output, or a remote command that does not complete.

    To end an unresponsive program, type CTRL + C. To view any errors that might
    have been reported, type "$error" in the local host and the remote session.

SEE ALSO
    Online version: http://go.microsoft.com/fwlink/?LinkID=135188
    about_remote
    about_remote_requirements


about_Requires

TOPIC
    about_Requires

SHORT DESCRIPTION
    Prevents a script from running by requiring the specified snap-ins and
    version.

LONG DESCRIPTION
    The #Requires statement prevents a script from running unless the Windows
    PowerShell version, snap-in, and snap-in version prerequisites are met. If
    the prerequisites are not met, Windows PowerShell does not run the script.

    You can use #Requires statements in any script. You cannot use them in
    functions, cmdlets, or snap-ins.

  Syntax

      Use the following syntax to specify the snap-in and the version of the
      snap-in that you want to require:

          #requires –PsSnapIn <PsSnapIn> [-Version <N>[.<n>]]

      Use the following syntax to specify the minimum version of
      Windows PowerShell that you want to require:

          #requires -Version <N>[.<n>]

      Use the following syntax to specify the shell that you want to require:

          #requires –ShellId <ShellId>

  Rules for Use

      - The #Requires statement must be the first item on a line in a script.

      - A script can include more than one #Requires statement.

      - The #Requires statements can appear on any line in a script.

  Examples

      The following statement requires the Microsoft.PowerShell.Security
      snap-in:

          #requires –PsSnapIn Microsoft.PowerShell.Security

      If the Microsoft.PowerShell.Security snap-in is not loaded, the script
      does not run, and Windows PowerShell displays the following error
      message:

          "The script '<script-name>' cannot be run because the following
          Windows PowerShell snap-ins that are specified by its "#requires"
          statements are missing: Microsoft.PowerShell.Security."

      The following statement requires the Windows PowerShell 2.0 version or
      any later version of the Microsoft.PowerShell.Security snap-in:

          #requires –PsSnapIn Microsoft.PowerShell.Security –Version 2

      The following statement requires Windows PowerShell 2.0 or a later
      version:

          #requires –Version 2.0

      The following script has two #Requires statements. The requirements
      specified in both statements must be met. Otherwise, the script will not
      run. Each #Requires statement must be the first item on a line:

          #requires –PsSnapIn Microsoft.PowerShell.Security –Version 2
          Get-WMIObject WIN32_LogicalDisk | out-file K:\status\DiskStatus.txt
          #requires –Version 2

      The following #Requires statement prevents a script from running if the
      specified shell ID does not match the current shell ID. The current
      shell ID is stored in the $ShellId variable:

          #requires –ShellId MyLocalShell

SEE ALSO
    about_Automatic_Variables
    about_Language_Keywords
    about_PSSnapins
    get-PSSnapin


about_Reserved_Words

TOPIC
    about_Reserved_Words

SHORT DESCRIPTION
    Lists the reserved words that cannot be used as identifiers because they
    have a special meaning in Windows PowerShell.

LONG DESCRIPTION
    There are certain words that have special meaning in Windows PowerShell.
    When these words appear without quotation marks, Windows PowerShell
    attempts to apply their special meaning rather than treating them as
    character strings. To use these words as parameter arguments in a command
    or script without invoking their special meaning, enclose the reserved
    words in quotation marks.

    The following are the reserved words in Windows PowerShell:

        Break
        Continue
        Do
        Else
        Elseif
        Filter
        For
        Foreach
        Function
        If
        In
        Local
        Private
        Return
        Switch
        Until
        Where
        While

    For information about language statements, such as Foreach, If,
    For, and While, type "get-help", type the prefix "about_", and then type
    the name of the statement. For example, to get information about the
    Foreach statement, type:

    get-help about_foreach

    For information about the Filter statement or the Return statement
    syntax, type:

        get-help about_functions

SEE ALSO
    about_Command_Syntax
    about_Escape_Characters
    about_Language_Keywords
    about_Parsing
    about_Quoting_Rules
    about_Script_Blocks
    about_Special_Characters


about_Return

TOPIC
    about_Return

SHORT DESCRIPTION
    Exits the current scope, which can be a function, script, or script block.

LONG DESCRIPTION
    The Return keyword exits a function, script, or script block. It can be
    used to exit a scope at a specific point, to return a value, or to indicate
    that the end of the scope has been reached.

    Users who are familiar with languages like C or C# might want to use the
    Return keyword to make the logic of leaving a scope explicit.

    In Windows PowerShell, the results of each statement are returned as
    output, even without a statement that contains the Return keyword.
    Languages like C or C# return only the value or values that are specified
    by the Return keyword.

  Syntax

      The syntax for the Return keyword is as follows:

          return [<expression>]

      The Return keyword can appear alone, or it can be followed by a value or
      expression, as follows:

          return
          return $a
          return (2 + $a)

  Examples

      The following example uses the Return keyword to exit a function at a
      specific point if a conditional is met:

          function ScreenPassword($instance)
          {
              if (!($instance.screensaversecure)) {return $instance.name}
              <additional statements>
          }

          foreach ($a in @(get-wmiobject win32_desktop)) { ScreenPassword($a) }

      This script checks each user account. The ScreenPassword function returns
      the name of any user account that does not have a password-protected
      screen saver. If the screen saver is password protected, the function
      completes any other statements to be run, and Windows PowerShell does not
      return any value.

      In Windows PowerShell, values can be returned even if the Return keyword
      is not used. The results of each statement are returned. For example, the
      following statements return the value of the $a variable:

          $a
          return

      The following statement also returns the value of $a:

          return $a

      The following example includes a statement intended to let the user know
      that the function is performing a calculation:

          function calculation {
              param ($value)

              "Please wait. Working on calculation..."
              $value += 73
              return $value
              }

      Running this function and assigning the result to a variable has the
      following effect:

          C:\PS> $a = calculation 14
          C:\PS>

      The "Please wait. Working on calculation..." string is not displayed.
      Instead, it is assigned to the $a variable, as in the following example:

          C:\PS> $a
          Please wait. Working on calculation...
          87

      Both the informational string and the result of the calculation are
      returned by the function and assigned to the $a variable.

SEE ALSO
    about_Functions
    about_Scopes
    about_Script_Blocks


about_Scopes

TOPIC
    about_Scopes

SHORT DESCRIPTION
    Explains the concept of scope in Windows PowerShell and shows how to set
    and change the scope of elements.

LONG DESCRIPTION
    Windows PowerShell protects access to variables, aliases, functions, and
    Windows PowerShell drives (PSDrives) by limiting where they can be read and
    changed. By enforcing a few simple rules for scope, Windows PowerShell
    helps to ensure that you do not inadvertently change an item that should
    not be changed.

    The following are the basic rules of scope:

        - An item you include in a scope is visible in the scope in which it
          was created and in any child scope, unless you explicitly make it
          private. You can place variables, aliases, functions, or Windows
          PowerShell drives in one or more scopes.

        - An item that you created within a scope can be changed only in the
          scope in which it was created, unless you explicitly specify a
          different scope.

    If you create an item in a scope, and the item shares its name with an
    item in a different scope, the original item might be hidden under the
    new item. But, it is not overridden or changed.

  Windows PowerShell Scopes

    Scopes in Windows PowerShell have both names and numbers. The named
    scopes specify an absolute scope. The numbers are relative and reflect
    the relationship between scopes.

    Global:
        The scope that is in effect when Windows PowerShell
        starts. Variables and functions that are present when
        Windows PowerShell starts have been created in the
        global scope. This includes automatic variables and
        preference variables. This also includes the variables, aliases,
        and functions that are in your Windows PowerShell
        profiles.

    Local:
        The current scope. The local scope can be the global
        scope or any other scope.

    Script:
        The scope that is created while a script file runs. Only
        the commands in the script run in the script scope. To
        the commands in a script, the script scope is the local
        scope.

    Private:
        Items in private scope cannot be seen outside of the current
        scope. You can use private scope to create a private version
        of an item with the same name in another scope.

    Numbered Scopes:
        You can refer to scopes by name or by a number that
        describes the relative position of one scope to another.
        Scope 0 represents the current, or local, scope. Scope 1
        indicates the immediate parent scope. Scope 2 indicates the
        parent of the parent scope, and so on. Numbered scopes
        are useful if you have created many recursive
        scopes.

 Parent and Child Scopes

    You can create a new scope by running a script or function, by creating
    a session, or by starting a new instance of Windows PowerShell. When you
    create a new scope, the result is a parent scope (the original scope) and
    a child scope (the scope that you created).

    In Windows PowerShell, all scopes are child scopes of the global scope,
    but you can create many scopes and many recursive scopes.

    Unless you explicitly make the items private, the items in the parent scope
    are available to the child scope. However, items that you create and change
    in the child scope do not affect the parent scope, unless you explicitly
    specify the scope when you create the items.

 Inheritance

    A child scope does not inherit the variables, aliases, and functions from
    the parent scope. Unless an item is private, the child scope can view the
    items in the parent scope. And, it can change the items by explicitly
    specifying the parent scope, but the items are not part of the child scope.

    However, a child scope is created with a set of items. Typically, it
    includes all the aliases that have the AllScope option. This option is
    discussed later in this topic. It includes all the variables that have the
    AllScope option, plus some variables that can be used to customize the
    scope, such as MaximumFunctionCount.

    To find the items in a particular scope, use the Scope parameter of
    Get-Variable or Get-Alias.

    For example, to get all the variables in the local scope, type:

    get-variable -scope local

    To get all the variables in the global scope, type:

    get-variable -scope global

 Scope Modifiers

    To specify the scope of a new variable, alias, or function, use a scope
    modifier. The valid values of a modifier are Global and Script.

    The syntax for a scope modifier in a variable is:

        $[<scope-modifier>]:<name> = <value>

    The syntax for a scope modifier in a function is:

        function [<scope-modifier>]:<name> {<function-body>}

    The default scope for scripts is the script scope. The default scope for
    functions and aliases is the local scope, even if they are defined in a
    script.

    The following command, which does not use a scope modifier, creates a
    variable in the current or local scope:

       $a = "one"

    To create the same variable in the global scope, use the Global scope
    modifier:

       $global:a = "one"

    To create the same variable in the script scope, use the script
    scope modifier:

       $script:a = "one"

    You can also use a scope modifier in functions. The following function
    definition creates a function in the global scope:

       function global:Hello
       {
        write-host "Hello, World"
       }

    You can also use scope modifiers to refer to a variable in a different
    scope. The following command refers to the $test variable, first in the
    local scope and then in the global scope:

      $test

      $global:test

 The AllScope Option

    Variables and aliases have an Option property that can take a value of
    AllScope. Items that have the AllScope property become part of any child
    scopes that you create, although they are not retroactively inherited by
    parent scopes.

    An item that has the AllScope property is visible in the child scope, and
    it is part of that scope. Changes to the item in any scope affect all the
    scopes in which the variable is defined.

 Managing Scope

    Several cmdlets have a Scope parameter that lets you get or set (create
    and change) items in a particular scope. Use the following command to find
    all the cmdlets in your session that have a Scope parameter:

         get-help * -parameter scope

    To find the variables that are visible in a particular scope, use the
    Scope parameter of Get-Variable. The visible parameters include global
    parameters, parameters in the parent scope, and parameters in the current
    scope.

    For example, the following command gets the variables that are visible in
    the local scope:

        get-variable -scope local

    To create a variable in a particular scope, use a scope modifier or the
    Scope parameter of Set-Variable. The following command creates a variable
    in the global scope:

    new-variable -scope global -name a -value "One"

    You can also use the Scope parameter of the New-Alias, Set-Alias, or
    Get-Alias cmdlets to specify the scope. The following command creates an
    alias in the global scope:

    new-alias -scope global -name np -value Notepad.exe

    To get the functions in a particular scope, use the Get-Item cmdlet when
    you are in the scope. The Get-Item cmdlet does not have a scope parameter.

 Using Dot Source Notation with Scope

    Scripts and functions follow all the rules of scope. You create them in a
    particular scope, and they affect only that scope unless you use a cmdlet
    parameter or a scope modifier to change that scope.

    But, you can add a script or function to the current scope by using dot
    source notation. Then, when a script runs in the current scope, any
    functions, aliases, and variables that the script creates are available
    in the current scope.

    To add a function to the current scope, type a dot (.) and a space before
    the path and name of the function in the function call.

    For example, to run the Sample.ps1 script from the C:\Scripts directory in
    the script scope (the default for scripts), use the following command:

        c:\scripts\sample.ps1

    To run the Sample.ps1 script in the local scope, use the following command:

        . c:\scripts.sample.ps1

    When you use the call operator (&) to run a function or script, it is not
    added to the current scope. The following example uses the call operator:

        & c:\scripts.sample.ps1

    Any aliases, functions, or variables that the Sample.ps1 script creates
    are not available in the current scope.

 Restricting Without Scope

    A few Windows PowerShell concepts are similar to scope or interact with
    scope. These concepts may be confused with scope or the behavior of scope.

    Sessions, modules, and nested prompts are self-contained environments,
    but they are not child scopes of the global scope in the session.

    Sessions:
        A session is an environment in which Windows PowerShell runs.
        When you create a session on a remote computer, Windows
        PowerShell establishes a persistent connection to the remote
        computer. The persistent connection lets you use the session for
        multiple related commands.

        Because a session is a contained environment, it has its own
        scope, but a session is not a child scope of the session in
        which is was created. The session starts with its own global
        scope. This scope is independent of the global scope of the session.
        You can create child scopes in the session. For example, you can run
        a script to create a child scope in a session.

    Modules:
        You can use a Windows PowerShell module to share and deliver
        Windows PowerShell tools. A module is a unit that can contain
        cmdlets, scripts, functions, variables, aliases, and other useful
        items. Unless explicitly defined, the items in a module are not
        accessible outside the module. Therefore, you can add the module to
        your session and use the public items without worrying that the
        other items might override the cmdlets, scripts, functions, and other
        items in your session.

        The privacy of a module behaves like a scope, but adding a module
        to a session does not change the scope. And, the module does not have
        its own scope, although the scripts in the module, like all Windows
        PowerShell scripts, do have their own scope.

    Nested Prompts:
        Similarly, nested prompts do not have their own scope. When you enter
        a nested prompt, the nested prompt is a subset of the environment.
        But, you remain within the local scope.

        Scripts do have their own scope. If you are debugging a script, and
        you reach a breakpoint in the script, you enter the script scope.

    Private Option:
        Aliases and variables have an Option property that can take a value
        of Private. Items that have the Private option can be viewed and
        changed in the scope in which they are created, but they cannot be
        viewed or changed outside that scope.

        For example, if you create a variable that has a private option in the
        global scope and then run a script, Get-Variable commands in the script
        do not display the private variable. This occurs even if you use
        the global scope modifier.

        You can use the Option parameter of the New-Variable, Set-Variable,
        New-Alias, and Set-Alias cmdlets to set the value of the Option
        property to Private.

    Visibility:
        The Visibility property of a variable or alias determines whether you
        can see the item outside the container, such as a module, in which it
        was created. Visibility is designed for containers in the same way that
        the Private value of the Option property is designed for scopes.

        The Visibility property takes the Public and Private values. Items
        that have private visibility can be viewed and changed only in the
        container in which they were created. If the container is added or
        imported, the items that have private visibility cannot be viewed or
        changed.

        Because Visibility is designed for containers, it works differently
        in a scope. If you create an item that has private visibility in the
        global scope, you cannot view or change the item in any scope. If you
        try to view or change the value of a variable that has private
        visibility, Windows PowerShell returns an error message.

        You can use the New-Variable and Set-Variable cmdlets to create a
        variable that has private visibility.

EXAMPLES

  Example 1: Change a Variable Value Only in a Script

      The following command changes the value of the $ConfirmPreference
      variable in a script. The change does not affect the global scope.

      First, to display the value of the $ConfirmPreference variable in
      the local scope, use the following command:

          C:\PS> $ConfirmPreference
          High

      Create a Scope.ps1 script that contains the following commands:

          $ConfirmPreference = "Low"
          "The value of `$ConfirmPreference is $ConfirmPreference."

      Run the script. The script changes the value of the $ConfirmPreference
      variable and then reports its value in the script scope. The output
      should resemble the following output:

          The value of $ConfirmPreference is Low.

      Next, test the current value of the $ConfirmPreference variable in the
      current scope.

          C:\PS> $ConfirmPreference
          High

      This example shows that changes to the value of a variable in the script
      scope do not affect the value of that variable in the parent scope.

  Example 2: View a Variable Value in Different Scopes

      You can use scope modifiers to view the value of a variable in the local
      scope and in a parent scope.

      First, define a $test variable in the global scope.

      $test = "Global"

      Next, create a Sample.ps1 script that defines the $test
      variable. In the script, use a scope modifier to refer
      to either the global or local versions of the $test variable.

          # In Sample.ps1

          $test = "Local"
          "The local value of `$test is $test."
          "The global value of `$test is $global:test."

      When you run Sample.ps1, the output should resemble the following output:

          The local value of $test is Local.
          The global value of $test is Global.

      When the script is complete, only the global value of $test is defined
      in the session.

          C:\PS> $test
          Global

  Example 3: Change the Value of a Variable in a Parent Scope

      Unless you protect an item by using the Private option or another
      method, you can view and change the value of a variable in a parent
      scope.

      First, define a $test variable in the global scope.

      $test = "Global"

      Next, create a Sample.ps1 script that defines the $test variable. In the
      script, use a scope modifier to refer to either the global or local
      versions of the $test variable.

          # In Sample.ps1

          $global:test = "Local"
          "The global value of `$test is $global:test."

      When the script is complete, the global value of $test is changed.

          C:\PS> $test
          Local

  Example 4: Creating a Private Variable

      A private variable is a variable that has an Option property that has a
      value of Private. Private variables are inherited by the child scope, but
      they can be viewed or changed only in the scope in which they were
      created.

      The following command creates a private variable called $ptest in the
      local scope.

      new-variable -name ptest -value 1 -option private

      You can display and change the value of $ptest in the local scope.

      C:\PS> $ptest
          1
          C:\PS> $ptest = 2
          C:\PS> $ptest
      2

      Next, create a Sample.ps1 script that contains the following commands.
      The command tries to display and change the value of $ptest.

          # In Sample.ps1

          "The value of `$Ptest is $Ptest."
            "The value of `$Ptest is $global:Ptest."

      Because the $ptest variable is not visible in the script scope, the
      output is empty.

          "The value of $Ptest is ."
            "The value of $Ptest is ."

SEE ALSO
    about_Variables
    about_Environment_Variables
    about_Functions
    about_Script_Blocks


about_Script_Blocks

TOPIC
    about_Script_Blocks

SHORT DESCRIPTION
    Defines what a script block is and explains how to use script blocks in
    the Windows PowerShell programming language.

LONG DESCRIPTION
    In the Windows PowerShell programming language, a script block is a
    collection of statements or expressions that can be used as a single unit.
    A script block can accept arguments and return values.

    Syntactically, a script block is a statement list in braces, as shown in
    the following syntax:

        {<statement list>}

    A script block returns the output of all the commands in the script block,
    either as a single object or as an array.

    Like functions, a script block can include parameters. Use the Param
    keyword to assign named parameters, as shown in the following syntax:

        {
            param ([type]$parameter1 [,[type]$parameter2])
            <statement list>
        }

    In a script block, unlike a function, you cannot specify parameters outside
    the braces.

    Like functions, script blocks can include the DynamicParam, Begin, Process,
    and End keywords. For more information, see about_Functions and
    about_Functions_Advanced.

  Using Script Blocks

      A script block is an instance of a Microsoft .NET Framework type
      (System.Management.Automation.ScriptBlock). Commands can have script
      block parameter values. For example, the Invoke-Command cmdlet has a
      ScriptBlock parameter that takes a script block value, as shown in this
      example:

          C:\PS> invoke-command -scriptblock  { get-process }
          Handles  NPM(K)    PM(K)     WS(K) VM(M)   CPU(s)     Id ProcessName
          -------  ------    -----     ----- -----   ------     -- -----------
              999      28    39100     45020   262    15.88   1844 communicator
              721      28    32696     36536   222    20.84   4028 explorer
          . . .

      The script block that is used as a value can be more complicated, as
      shown in the following example:

          C:\PS> invoke-command -scriptblock { param ($uu = "Parameter");
              "$uu assigned." }
          Parameter assigned.

      The script block in the preceding example uses the Param keyword to
      create a parameter that has a default value. The following example uses
      the Args parameter of the Invoke-Command cmdlet to assign a different
      value to the parameter:

          C:\PS> invoke-command -scriptblock {param ($uu = "Parameter");
              "$uu assigned."} -args "Other value"
          Other value assigned.

      You can assign a script block to a variable, as shown in the following
      example:

          C:\PS> $a = {param ($uu = "Parameter"); "$uu assigned."}

      You can use the variable with a cmdlet such as Invoke-Command, as shown
      in the following example:

          C:\PS> invoke-command -scriptblock $a -args "Other value"
          Other value assigned.

      You can run a script block that is assigned to a variable by using the
      call operator (&), as shown in the following example:

          C:\PS> &$a
          Parameter assigned.

      You can also provide a parameter to the script block, as shown in the
      following example:

          C:\PS> &$a "Other value"
          Other value assigned.

      If you want to assign the value that is created by a script block to a
      variable, use the call operator to run the script block directly, as
      shown in the following example:

          C:\PS> $a = &{param ($uu = "Parameter"); "$uu assigned."}
          C:\PS> $a
          Parameter assigned.

      For more information about the call operator, see about_Operators.

SEE ALSO
    about_Functions
    about_Functions_Advanced
    about_Operators


about_Script_Internationalization

TOPIC
    about_Script_Internationalization

SHORT DESCRIPTION
    Describes the script internationalization features of Windows PowerShell 2.0
    that make it easy for scripts to display messages and instructions to users
    in their user interface (UI) language.

LONG DESCRIPTION
    The Windows PowerShell script internationalization features allow you to
    better serve users throughout the world by displaying Help and user
    messages for scripts and functions in the user's UI language.

    The script internationalization features query the UI culture of the
    operating system during execution, import the appropriate
    translated text strings, and display them to the user. The Data section
    lets you store text strings separate from code so they are easily
    identified and extracted. A new cmdlet, ConvertFrom-StringData,
    converts text strings into dictionary-like hash tables to facilitate
    translation.

    The Windows PowerShell 2.0 features used in script internationalization
    are not supported by Windows PowerShell 1.0. Scripts that include these
    features will not run in Windows PowerShell 1.0 without modification.

    To support international Help text, Windows PowerShell 2.0 includes the
    following features:

       -- A Data section that separates text strings from code instructions. For
          more information about the Data section, see about_Data_Sections.

       -- New automatic variables, $PSCulture and $PSUICulture. $PSCulture stores
          the name of the UI language used on the system for elements such as
          the date, time, and currency. The $PSUICulture variable stores the
          name of the UI language used on the system for user interface elements
          such as menus and text strings.

       -- A cmdlet, ConvertFrom-StringData, that converts text strings into
          dictionary-like hash tables to facilitate translation. For more
          information, see ConvertFrom-StringData.

       -- A new file type, .psd1, that stores translated text strings. The .psd1
          files are stored in language-specific subdirectories of the script
          directory.

       -- A cmdlet, Import-LocalizedData, that imports translated text strings
          for a specified language into a script at runtime. This cmdlet recognizes
          and imports strings in any Windows-supported language. For more
          information see Import-LocalizedData.

 THE DATA SECTION: Storing Default Strings

     Use a Data section in the script to store the text strings in the default language.
     Arrange the strings in key/value pairs in a here-string. Each key/value pair must
     be on a separate line. If you include comments, the comments must be on separate
     lines.

     The ConvertFrom-StringData cmdlet converts the key/value pairs in the here-string
     into a dictionary-like hash table that is stored in the value of the Data section
     variable.

     In the following example, the Data section of the World.ps1 script includes
     the English-United States (en-US) set of prompt messages for a script. The
     ConvertFrom-StringData cmdlet converts the strings into a hash table and stores
     them in the $msgtable variable.

    $msgTable = Data {
        # culture="en-US"
        ConvertFrom-StringData @'
        helloWorld = Hello, World.
            errorMsg1 = You cannot leave the user name field blank.
             promptMsg = Please enter your user name.
    '@
    }

     For more information about here-strings, see about_Quoting_Rules.

 PSD1 FILES: Storing Translated Strings

    Save the script messages for each UI language in separate text files with
    the same name as the script and the .psd1 file name extension. Store the files
    in subdirectories of the script directory with names of cultures in the following
    format:

    <language>–<region>

    Examples: de-DE, ar-SA, and zh-Hans

    For example, if the World.ps1 script is stored in the C:\Scripts directory, you
    would create a file directory structure that resembles the following:

    C:\Scripts
    C:\Scripts\World.ps1
        C:\Scripts\de-DE\World.psd1
            C:\Scripts\ar-SA\World.psd1
            C:\Scripts\zh-CN\World.psd1
        ...

    The World.psd1 file in the de-DE subdirectory of the script directory
    might include the following statement:

        ConvertFrom-StringData @'
        helloWorld = Hello, World (in German).
        errorMsg1 = You cannot leave the user name field blank (in German).
            promptMsg = Please enter your user name (in German).
    '@

    Similarly, the World.psd1 file in the ar-SA subdirectory of the script directory
    might includes the following statement:

        ConvertFrom-StringData @'
        helloWorld = Hello, World (in Arabic).
        errorMsg1 = You cannot leave the user name field blank (in Arabic).
            promptMsg = Please enter your user name (in Arabic).
    '@

 IMPORT-LOCALIZEDDATA: Dynamic Retrieval of Translated Strings

    To retrieve the strings in the UI language of the current user, use
    the Import-LocalizedData cmdlet.

    Import-LocalizedData finds the value of the $PSUICulture automatic
    variable and imports the content of the <script-name>.psd1 files in
    the subdirectory that matches the $PSUICulture value. Then, it saves
    the imported content in the variable specified by the value of the
    BindingVariable parameter.

    import-localizeddata -bindingVariable msgTable

    For example, if the Import-LocalizedData command appears in the
    C:\Scripts\World.ps1 script and the value of $PSUICulture is
    "ar-SA", Import-LocalizedData finds the following file:

         C:\Scripts\ar-SA\World.psd1

    Then, it imports the Arabic text strings from the file into
    the $msgTable variable, replacing any default strings that might
    be defined in the Data section of the World.ps1 script.

    As a result, when the script uses the $msgTable variable
    to display user messages, the messages are displayed in
    Arabic.

    For example, the following script displays the "Please enter your user
    name" message in Arabic:

    if (!($username)) { $msgTable.promptMsg }

    If Import-LocalizedData cannot find a .psd1 file that matches the
    value of $PSUIculture, the value of $msgTable is not replaced,
    and the call to $msgTable.promptMsg displays the fallback en-US
    strings.

 ExAMPLE

    This example shows how the script internationalization features
    are used in a script to display a day of the week to users
    in the language that is set on the computer.

    The following is a complete listing of the Sample1.ps1 script
    file.

    The script begins with a Data section named Day ($Day) that
    contains a ConvertFrom-StringData command. The expression
    submitted to ConvertFrom-StringData is a here-string that
    contains the day names in the default UI culture, en-US, in
    key/value pairs. The ConvertFrom-StringData cmdlet converts
    the key/value pairs in the here-string into a hash table and
    then saves it in the value of the $Day variable.

    The Import-LocalizedData command imports the contents of the
    .psd1 file in the directory that matches the value of the
    $PSUICulture automatic variable and then saves it in the $Day
    variable, replacing the values of $Day that are defined in the
    Data section.

    The remaining commands load the strings into an array and display
    them.

        $Day = DATA {
    # culture="en-US"
    ConvertFrom-StringData @'
        messageDate = Today is
        d1 = Monday
        d2 = Tuesday
        d3 = Wednesday
        d4 = Thursday
        d5 = Friday
        d6 = Saturday
        d7 = Sunday
        '@
    }

    Import-LocalizedData -BindingVariable Day

    # Build an array of weekdays.
    $a = $Day.d1, $Day.d2, $Day.d3, $Day.d4, $Day.d5, $Day.d6, $Day.d7

        # Get the day of the week as a number (Monday = 1).
        # Index into $a to get the name of the day.
        # Use string formatting to build a sentence.

        "{0} {1}" –f $Day.messageDate, $a[(get-date -uformat %u)] | Out-Host

    The .psd1 files that support the script are saved in subdirectories of
    the script directory with names that match the $PSUICulture values.

    The following is a complete listing of .\de-DE\sample1.psd1:

        # culture="en-US"
    ConvertFrom-StringData @'
        messageDate = Today is
        d1 = Monday (in German)
        d2 = Tuesday (in German)
        d3 = Wednesday (in German)
        d4 = Thursday (in German)
            d5 = Friday (in German)
            d6 = Saturday (in German)
            d7 = Sunday (in German)
        '@

    As a result, when you run Sample.ps1 on a system on which the value
    of $PSUICulture is de-DE, the output of the script is:

    Today is Friday (in German)

SEE ALSO
    about_Data_Sections
    about_Automatic_Variables
    about_Hash_Tables
    about_Quoting_Rules
    ConvertFrom-StringData
    Import-LocalizedData


about_Scripts

TOPIC
    about_Scripts

SHORT DESCRIPTION
    Describes how to write and run scripts in Windows PowerShell.

LONG DESCRIPTION
    A script is a plain text file that contains one or more Windows PowerShell
    commands. Windows PowerShell scripts have a .ps1 file name extension.

    Writing a script saves a command for later use and makes it easy to share
    with others. Most importantly, it lets you run the commands simply by typing
    the script path and the file name. Scripts can be as simple as a single
    command in a file or as extensive as a complex program.

    Scripts have additional features, such as the #Requires special comment,
    the use of parameters, support for data sections, and digital signing for
    security. You can also write Help topics for scripts and for any functions
    in the script.

  HOW TO WRITE A SCRIPT

    A script can contain any valid Windows PowerShell commands, including single
    commands, commands that use the pipeline, functions, and control structures
    such as If statements and For loops.

    To write a script, start a text editor (such as Notepad) or a script editor
    (such as the Windows PowerShell Integrated Scripting Environment [ISE]). Type
    the commands and save them in a file with a valid file name and the .ps1 file
    name extension.

    The following example is a simple script that gets the services that are
    running on the current system and saves them to a log file. The log file name
    is created from the current date.

        $date = (get-date).dayofyear
        get-service | out-file "$date.log"

    To create this script, open a text editor or a script editor, type these
    commands, and then save them in a file named ServiceLog.ps1.

  HOW TO RUN A SCRIPT

    Before you can run a script, you need to change the default Windows
    PowerShell execution policy. The default execution policy, "Restricted",
    prevents all scripts from running, including scripts that you write on the
    local computer. For more information, see about_Execution_Policies.

    To run a script, type the full name and the full path to the script file.

    For example, to run the ServicesLog script in the C:\Scripts directory, type:

        c:\scripts\ServicesLog.ps1

    To run a script in the current directory, type the path to the current
    directory, or use a dot to represent the current directory, followed by
    a path backslash (.\).

    For example, to run the ServicesLog.ps1 script in the local directory, type:

        .\ServicesLog.ps1

    As a security feature, Windows PowerShell does not run scripts when you
    double-click the script icon in Windows Explorer or when you type the
    script name without a full path, even when the script is in the current
    directory. For more information about running commands and scripts in
    Windows PowerShell, see about_Command_Precedence.

  RUNNING SCRIPTS REMOTELY

    To run a script on a remote computer, use the FilePath parameter of the
    Invoke-Command cmdlet.

    Enter the path and file name of the script as the value of the FilePath
    parameter. The script must reside on the local computer or in a directory
    that the local computer can access.

    The following command runs the ServicesLog.ps1 script on the Server01 remote
    computer.

        invoke-command -computername Server01 -filepath C:\scripts\servicesLog.ps1

  PARAMETERS IN SCRIPTS

    To define parameters in a script, use a Param statement. The Param statement
    must be the first statement in a script, except for comments and any
    #Requires statements.

    Script parameters work like function parameters. The parameter values are
    available to all of the commands in the script. All of the features of
    function parameters, including the Parameter attribute and its named
    arguments, are also valid in scripts.

    When running the script, script users type the parameters after the script
    name.

    The following example shows a Test-Remote.ps1 script that has a ComputerName
    parameter. Both of the script functions can access the ComputerName
    parameter value.

        param ($ComputerName = $(throw "ComputerName parameter is required."))

        function CanPing {
           $error.clear()
           $tmp = test-connection $computername -erroraction SilentlyContinue

           if (!$?)
               {write-host "Ping failed: $ComputerName."; return $false}
           else
               {write-host "Ping succeeded: $ComputerName"; return $true}
        }

        function CanRemote {
            $s = new-pssession $computername -erroraction SilentlyContinue

            if ($s -is [System.Management.Automation.Runspaces.PSSession])
                {write-host "Remote test succeeded: $ComputerName."}
            else
                {write-host "Remote test failed: $ComputerName."}
        }

        if (CanPing $computername) {CanRemote $computername}

    To run this script, type the parameter name after the script name.
    For example:

    C:\PS> .\test-remote.ps1 -computername Server01

    Ping succeeded: Server01
    Remote test failed: Server01

    For more information about the Param statement and the function parameters,
    see about_Functions and about_Functions_Advanced_Parameters.

  HELP FOR SCRIPTS

    The Get-Help cmdlet gets Help for scripts as well as for cmdlets,
    providers, and functions. To get Help for a script, type Get-Help and the
    path and file name of the script. If the script path is in your Path
    environment variable, you can omit the path.

    For example, to get Help for the ServicesLog.ps1 script, type:

        get-help C:\admin\scripts\ServicesLog.ps1

    You can write Help for a script by using either of the two following methods:

    --  Comment-Based Help for Scripts

        Create a Help topic by using special keywords in the comments. To create
        comment-based Help for a script, the comments must be placed at the
        beginning or end of the script file. For more information about
        comment-based Help, see about_Comment_Based_Help.

    --  XML-Based Help  for Scripts

        Create an XML-based Help topic, such as the type that is typically
        created for cmdlets. XML-based Help is required if you are translating
        Help topics into multiple languages.

        To associate the script with the XML-based Help topic, use the
        .ExternalHelp Help comment keyword. For more information about the
        ExternalHelp keyword, see about_Comment_Based_Help. For more information
        about XML-based help, see "How to Write Cmdlet Help" in the MSDN
        (Microsoft Developer Network) library at
        http://go.microsoft.com/fwlink/?LinkID=123415.

  SCRIPT SCOPE AND DOT SOURCING

    Each script runs in its own scope. The functions, variables, aliases, and
    drives that are created in the script exist only in the script scope. You
    cannot access these items or their values in the scope in which the
    script runs.

    To run a script in a different scope, you can specify a scope, such as
    Global or Local, or you can dot source the script.

    The dot sourcing feature lets you run a script in the current scope instead
    of in the script scope. When you run a script that is dot sourced, the
    commands in the script run as though you had typed them at the command
    prompt. The functions, variables, aliases, and drives that the script
    creates are created in the scope in which you are working. After the script
    runs, you can use the created items and access their values in your session.

    To dot source a script, type a dot (.) and a space before the script path.

    For example:

        . C:\scripts\UtilityFunctions.ps1

    -or-

        . .\UtilityFunctions.ps1

    After the UtilityFunctions script runs, the functions and variables that the
    script creates are added to the current scope.

    For example, the UtilityFunctions.ps1 script creates the New-Profile
    function and the $ProfileName variable.

        #In UtilityFunctions.ps1

        function New-Profile
        {
            Write-Host "Running New-Profile function"
            $profileName = split-path $profile -leaf

            if (test-path $profile)
               {write-error "There is already a $profileName profile on this computer."}
            else
           {new-item -type file -path $profile -force }
        }

    If you run the UtilityFunctions.ps1 script in its own script scope, the
    New-Profile function and the $ProfileName variable exist only while the
    script is running. When the script exits, the function and variable are
    removed, as shown in the following example.

        C:\PS> .\UtilityFunctions.ps1

        C:\PS> New-Profile
        The term 'new-profile' is not recognized as a cmdlet, function, operable
        program, or script file. Verify the term and try again.
        At line:1 char:12
        + new-profile <<<<
           + CategoryInfo          : ObjectNotFound: (new-profile:String) [],
           + FullyQualifiedErrorId : CommandNotFoundException

        C:\PS> $profileName
        C:\PS>

    When you dot source the script and run it, the script creates the
    New-Profile function and the $ProfileName variable in your session in your
    scope. After the script runs, you can use the New-Profile function in your
    session, as shown in the following example.

        C:\PS> . .\UtilityFunctions.ps1

        C:\PS> New-Profile

            Directory: C:\Users\juneb\Documents\WindowsPowerShell

            Mode    LastWriteTime     Length Name
            ----    -------------     ------ ----
            -a---   1/14/2009 3:08 PM      0 Microsoft.PowerShellISE_profile.ps1

        C:\PS> $profileName
        Microsoft.PowerShellISE_profile.ps1

    For more information about scope, see about_Scopes.

  SCRIPTS IN MODULES

    A module is a set of related Windows PowerShell resources that can be
    distributed as a unit. You can use modules to organize your scripts,
    functions, and other resources. You can also use modules to distribute your
    code to others, and to get code from trusted sources.

    You can include scripts in your modules, or you can create a script module,
    which is a module that consists entirely or primarily of a script and
    supporting resources. A script module is just a script with a .psm1 file
    name extension.

    For more information about modules, see about_Modules.

  OTHER SCRIPT FEATURES

    Windows PowerShell has many useful features that you can use in scripts.

    #Requires
        You can use a #Requires statement to prevent a script from running
        without specified modules or snap-ins and a specified version of
        Windows PowerShell. For more information, see about_Requires.

    $MyInvocation
        The $MyInvocation automatic variable contains information about the
        current command, including the current script. You can use this variable
        and its properties to get information about the script while it is
        running. For example, the $MyInvocation.MyCommand.Path variable contains
        the path and file name of the script.

    Data sections
        You can use the Data keyword to separate data from logic in scripts.
        Data sections can also make localization easier. For more information,
        see about_Data_Sections and about_Script_Localization.

    Script Signing
        You can add a digital signature to a script. Depending on the execution
        policy, you can use digital signatures to restrict the running of scripts
        that could include unsafe commands. For more information, see
        about_Execution_Policies and about_Signing.

SEE ALSO
    about_Command_Precedence
    about_Comment_Based_Help
    about_Execution_Policies
    about_Functions
    about_Modules
    about_Profiles
    about_Requires
    about_Scopes
    about_Script_Blocks
    about_Signing
    Invoke-Command


about_Session_Configurations

TOPIC
    about_Session_Configurations

SHORT DESCRIPTION
    Describes session configurations, which determine the users who can
    connect to the computer remotely and the commands they can run.

LONG DESCRIPTION
    A session configuration is a group of settings on the local computer
    that define the environment for the Windows PowerShell sessions that are
    created when remote users connect to the local computer.

    Administrators of the computer can use session configurations to protect
    the computer and to define custom environments for users who connect to
    the computer.

    Administrators can also use session configurations to determine the
    permissions that are required to connect to the computer remotely. By
    default, only members of the Administrators group have permission to
    use the session configuration to connect remotely, but you can change
    the default settings to allow all users, or selected users, to connect
    remotely to your computer.

    Session configurations are a feature of Web Services for Management
    (WS-Management) based Windows PowerShell remoting. They are used only
    when you use the New-PSSession, Invoke-Command, or Enter-PSSession cmdlets
    to connect to a remote computer.

    Note: To manage the session configurations on a computer that is running
          Windows Vista, Windows Server 2008, or a later version of Windows,
          start Windows PowerShell with the "Run as administrator" option.

  About Session Configurations

      Every Windows PowerShell session uses a session configuration. This
      includes persistent sessions that you create by using the New-PSSession
      or Enter-PSSession cmdlets, and the temporary sessions that Windows
      PowerShell creates when you use the ComputerName parameter of a cmdlet
      that uses WS-Management-based remoting technology, such as
      Invoke-Command.

      Administrators can use session configurations to protect the resources
      of the computer and to create custom environments for users who connect
      to the computer. For example, you can use a session configuration to
      limit the size of objects that the computer receives in the session,
      to define the language mode of the session, and to specify the cmdlets,
      providers, and functions that are available in the session.

      By configuring the security descriptor of a session configuration, you
      determine who can use the session configuration to connect to the
      computer. Users must have Execute permission to a session configuration
      to use it in a session. If a user does not have the required permissions
      to use any of the session configurations on a computer, the user cannot
      connect to the computer remotely.

      By default, only Administrators of the computer have permission to use
      the default session configurations. But, you can change the security
      descriptors to allow everyone, no one, or only selected users to use
      the session configurations on your computer.

  Default Session Configurations

      Windows PowerShell includes a built-in session configuration named
      Microsoft.PowerShell. On computers running 64-bit versions of Windows,
      Windows PowerShell also provides Microsoft.PowerShell32, a 32-bit
      session configuration.

      These session configurations are used for sessions by default, that is,
      when a command to create a session does not include the ConfigurationName
      parameter of the New-PSSession, Enter-PSSession, or Invoke-Command
      cmdlet.

      The security descriptors for the default session configurations allow
      only members of the Administrators group on the local computer to use
      them. As such, only members of the Administrators group can connect to
      the computer remotely unless you change the default settings.

      You can change the default session configurations by using the
      $PSSessionConfigurationName preference variable. For more information,
      see about_Preference_Variables.

  Viewing Session Configurations on the Local Computer

      To get the session configurations on your local computer, use the
      Get-PSSessionConfiguration cmdlet.

      For example, type:

        C:\PS> get-pssessionconfiguration | format-list -property name, permission

        Name       : microsoft.powershell
        Permission : BUILTIN\Administrators AccessAllowed

        Name       : microsoft.powershell32
        Permission : BUILTIN\Administrators AccessAllowed

      You can also use the WS-Management provider in Windows PowerShell to view
      session configurations. The WS-Management provider creates a WSMAN:
      drive in your session.

      In the WSMAN: drive, session configurations are in the Plugin node.
      (All session configurations are in the Plugin node, but there are items
      in the Plugin node that are not session configurations.)

      For example, to view the session configurations on the local computer,
      type:

         C:\PS> dir wsman:\localhost\plugin\microsoft*

                    WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin

         Name                      Type                 Keys
         ----                      ----                 ----
         microsoft.powershell      Container            {Name=microsoft.powershell}
         microsoft.powershell32    Container            {Name=microsoft.powershell}

  Viewing Session Configurations on a Remote Computer

      To view the session configurations on a remote computer, use the
      Connect-WSMan cmdlet to add a note for the remote computer to the WSMAN:
      drive on your local computer, and then use the WSMAN: drive to view
      the session configurations.

      For example, the following command adds a node for the Server01 remote
      computer to the WSMAN: drive on the local computer.

        C:\PS> connect-wsman server01.corp.fabrikam.com

      When the command is complete, you can navigate to the node for the
      Server01 computer to view the session configurations.

      For example:

        C:\PS> cd wsman:

        PS WSMan:\> dir

        ComputerName                                  Type
        ------------                                  ----
        localhost                                     Container
        server01.corp.fabrikam.com                    Container

        PS WSMan:\> dir server01*\plugin\*

               WSManConfig: Microsoft.WSMan.Management\WSMan::server01.corp.fabrikam.com\Plugin

        Name                      Type            Keys
        ----                      ----            ----
        microsoft.powershell      Container       {Name=microsoft.powershell}
        microsoft.powershell32    Container       {Name=microsoft.powershell32}

  Changing the Security Descriptor of a Session Configuration

      By default, members of the Administrators group on the computer have
      Execute permission to the default session configurations, but you can
      change the security descriptors on the default session configurations
      and on any session configurations that you create.

      To give other users permission to connect to the computer remotely,
      use the Set-PSSessionConfiguration cmdlet to add "Execute" permissions
      for those users to the security descriptors of the Microsoft.PowerShell
      and Microsoft.PowerShell32 session configurations.

      For example, the following command opens a property page that lets you
      change the security descriptor for the Microsoft.PowerShell default
      session configuration.

        C:\PS> set-pssessionConfiguration -name Microsoft.PowerShell -showSecurityDescriptorUI

      To deny everyone permission to all the session configurations on the
      computer, use the Disable-PSRemoting function or the
      Disable-PSSessionConfiguration cmdlet. For example, the following
      command adds a "Deny All" entry to all the session configurations on the
      computer.

        C:\PS> disable-psremoting

      To add a "Deny All" entry to a particular session configuration, use
      the Disable-PSSessionConfiguration cmdlet. For example, the following
      command adds a "Deny All" entry to the Microsoft.PowerShell session
      configuration.

        C:\PS> disable-pssessionConfiguration -name Microsoft.PowerShell

      To remove the "Deny All" entry from all the session configurations, use
      the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. For
      example, the following command removes the "Deny All" entry from the
      default session configurations.

        C:\PS> enable-pssessionConfiguration -name Microsoft.Power*

      To make other changes to the security descriptor of a session
      configuration, use the Set-PSSessionConfiguration cmdlet. Use the
      SecurityDescriptorSDDL parameter to submit an SDDL string value. Use the
      ShowSecurityDescriptorUI parameter to display a user interface property
      sheet that helps you to create a new SDDL.

      For example:

        C:\PS> set-pssessionConfiguration -name Microsoft.PowerShell -showSecurityDescriptorUI

  Creating a New Session Configuration

      To create a new session configuration on the local computer, use the
      Register-PSSessionConfiguration cmdlet. To define the new session
      configuration, you can use a C# assembly, a Window PowerShell script,
      and the parameters of the Register-PSSessionConfiguration cmdlet.

      For example, the following command creates a session configuration
      that is identical the Microsoft.PowerShell session configuration, except
      that it limits the data received from a remote command to 20 megabytes
      (MB). (The default is 50 MB).

        c:\PS> register-psSessionConfiguration -name NewConfig --MaximumReceivedDataSizePerCommandMB 20

      When you create a session configuration, you can manage it by using the
      other session configuration cmdlets, and it appears in the WSMAN: drive.

      For more information, see Register-PSSessionConfiguration.

  Removing a Session Configuration

      To remove a session configuration from the local computer, use the
      Unregister-PSSessionConfiguration cmdlet. For example, the following
      command removes the NewConfig session configuration from the computer.

        c:\PS> unregister-psSessionConfiguration -name NewConfig

      For more information, see Unregister-PSSessionConfiguration.

  Selecting a Session Configuration

      To select a particular session configuration for a session, use the
      ConfigurationName parameter of New-PSSession, Enter-PSSession, or
      Invoke-Command.

      For example, this command uses the New-PSSession cmdlet to start a
      PSSession on the Server01 computer. The command uses the
      ConfigurationName parameter to select the WithProfile configuration
      on the Server01 computer.

        C:\PS> new-pssession -computername Server01 -configurationName WithProfile

      This command will succeed only if the current user has permission to use
      the WithProfile session configuration or can supply the credentials of a
      user who has the required permissions.

      You can also use the $PSSessionConfigurationName preference variable to
      change the default session configuration on the computer. For more
      information about the $PSSessionConfigurationName preference variable,
      see about_Preference_Variables.

SEE ALSO
    about_Preference_Variables
    about_PSSession
    about_Remote
    New-PSSession
    Disable-PSSessionConfiguration
    Enable-PSSessionConfiguration
    Get-PSSessionConfiguration
    Register-PSSessionConfiguration
    Set-PSSessionConfiguration
    Unregister-PSSessionConfiguration


about_Signing

TOPIC
    about_signing

SHORT DESCRIPTION
    Explains to how sign scripts so that they comply with the Windows
    PowerShell execution policies.

LONG DESCRIPTION
    The Restricted execution policy does not permit any scripts to run.
    The AllSigned and RemoteSigned execution policies prevent Windows
    PowerShell from running scripts that do not have a digital signature.

    This topic explains how to run selected scripts that are not signed,
    even while the execution policy is RemoteSigned, and how to sign
    scripts for your own use.

    For more information about Windows PowerShell execution policies,
    see about_Execution_Policy.

 TO PERMIT SIGNED SCRIPTS TO RUN
 -------------------------------
    When you start Windows PowerShell on a computer for the first time, the
    Restricted execution policy (the default) is likely to be in effect.

    The Restricted policy does not permit any scripts to run.

    To find the effective execution policy on your computer, type:

        get-executionpolicy

    To run unsigned scripts that you write on your local computer and signed
    scripts from other users, use the following command to change the execution
    policy on the computer to RemoteSigned:

    set-executionpolicy remotesigned

    For more information, see Set-ExecutionPolicy.

 RUNNING UNSIGNED SCRIPTS (REMOTESIGNED EXECUTION POLICY)
 --------------------------------------------------------
    If your Windows PowerShell execution policy is RemoteSigned, Windows
    PowerShell will not run unsigned scripts that are downloaded from the
    Internet, including unsigned scripts you receive through e-mail and instant
    messaging programs.

    If you try to run a downloaded script, Windows PowerShell displays the
    following error message:

        The file <file-name> cannot be loaded. The file
        <file-name> is not digitally signed. The script
        will not execute on the system. Please see "Get-Help
        about_signing" for more details.

    Before you run the script, review the code to be sure that you trust it.
    Scripts have the same effect as any executable program.

    To run an unsigned script:

        1. Save the script file on your computer.
        2. Click Start, click My Computer, and locate the saved script file.
        3. Right-click the script file, and then click Properties.
        4. Click Unblock.

    If a script that was downloaded from the Internet is digitally signed, but
    you have not yet chosen to trust its publisher, Windows PowerShell displays
    the following message:

        Do you want to run software from this untrusted publisher?
        The file <file-name> is published by CN=<publisher-name>. This
        publisher is not trusted on your system. Only run scripts
        from trusted publishers.

        [V] Never run  [D] Do not run  [R] Run once  [A] Always run
        [?] Help (default is "D"):

        If you trust the publisher, select "Run once" or "Always run."
        If you do not trust the publisher, select either "Never run" or
        "Do not run." If you select "Never run" or "Always run," Windows
        PowerShell will not prompt you again for this publisher.

 METHODS OF SIGNING SCRIPTS
 --------------------------
    You can sign the scripts that you write and the scripts that you obtain
    from other sources. Before you sign any script, examine each command
    to verify that it is safe to run.

    For best practices about code signing, see "Code-Signing
    Best Practices" at http://go.microsoft.com/fwlink/?LinkId=119096.

    For more information about how to sign a script file, see
    Set-AuthenticodeSignature.

    To add a digital signature to a script, you must sign it with a code
    signing certificate. Two types of certificates are suitable for signing
    a script file:

        -- Certificates that are created by a certification authority:

           For a fee, a public certificate authority verifies your
           identity and gives you a code signing certificate.  When
           you purchase your certificate from a reputable certification
           authority, you are able to share your script with users
           on other computers that are running Windows because those other
           computers trust the certification authority.

        -- Certificates that you create:

           You can create a self-signed certificate for which
           your computer is the authority that creates the certificate.
           This certificate is free of charge and enables you to write,
           sign, and run scripts on your computer. However, a script
           signed by a self-signed certificate will not run on other
           computers.

    Typically, you would use a self-signed certificate only to sign
    scripts that you write for your own use and to sign scripts that you get
    from other sources that you have verified to be safe. It is not
    appropriate for scripts that will be shared, even within an enterprise.

    If you create a self-signed certificate, be sure to enable strong
    private key protection on your certificate. This prevents malicious
    programs from signing scripts on your behalf. The instructions are
    included at the end of this topic.

 CREATE A SELF-SIGNED CERTIFICATE
 --------------------------------
    To create a self-signed certificate, use the Certificate Creation
    tool (MakeCert.exe). This  tool is included in the Microsoft .NET Framework
    SDK (versions 1.1 and later) and in the Microsoft Windows SDK.

    For more information about the syntax and the parameter descriptions of the
    MakeCert.exe tool, see "Certificate Creation Tool (MakeCert.exe)" in the
    MSDN (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkId=119097.

    To use the MakeCert.exe tool to create a certificate, run the following
    commands in an SDK Command Prompt window.

    Note: The first command creates a local certification authority for
          your computer. The second command generates a personal
          certificate from the certification authority.

    Note: You can copy or type the commands exactly as they appear.
          No substitutions are necessary, although you can change the
          certificate name.

            makecert -n "CN=PowerShell Local Certificate Root" -a sha1 `
                -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer `
                -ss Root -sr localMachine

            makecert -pe -n "CN=PowerShell User" -ss MY -a sha1 `
                -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer

    The MakeCert.exe tool will prompt you for a private key password. The
    password ensures that no one can use or access the certificate without
    your consent. Create and enter a password that you can remember. You will
    use this password later to retrieve the certificate.

    To verify that the certificate was generated correctly, use the
    following command to get the certificate in the certificate
    store on the computer. (You will not find a certificate file in the
    file system directory.)

    At the Windows PowerShell prompt, type:

            get-childitem cert:\CurrentUser\my -codesigning

    This command uses the Windows PowerShell Certificate provider to view
    information about the certificate.

    If the certificate was created, the output shows the thumbprint
    that identifies the certificate in a display that resembles the following:

        Directory: Microsoft.PowerShell.Security\Certificate::CurrentUser\My

        Thumbprint                                Subject
        ----------                                -------
        4D4917CB140714BA5B81B96E0B18AAF2C4564FDF  CN=PowerShell User ]

 SIGN A SCRIPT
 -------------

    After you create a self-signed certificate, you can sign scripts. If you
    use the AllSigned execution policy, signing a script permits you to run
    the script on your computer.

    The following sample script, Add-Signature.ps1, signs a script. However,
    if you are using the AllSigned execution policy, you must sign the
    Add-Signature.ps1 script before you run it.

    To use this script, copy the following text into a text file, and
    name it Add-Signature.ps1.

    Note: Be sure that the script file does not have a .txt file name
          extension. If your text editor appends ".txt", enclose the file name
          in quotation marks: "add-signature.ps1".

            ## add-signature.ps1
            ## Signs a file
            param([string] $file=$(throw "Please specify a filename."))
            $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0]
            Set-AuthenticodeSignature $file $cert

    To sign the Add-Signature.ps1 script file, type the following commands at
    the Windows PowerShell command prompt:

        $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0]

        Set-AuthenticodeSignature add-signature.ps1 $cert

    After the script is signed, you can run it on the local computer.
    However, the script will not run on computers on which the Windows
    PowerShell execution policy requires a digital signature from a
    trusted authority. If you try, Windows PowerShell displays the following
    error message:

        The file C:\remote_file.ps1 cannot be loaded. The signature of the
        certificate cannot be verified.
        At line:1 char:15
        + .\ remote_file.ps1 <<<<

    If Windows PowerShell displays this message when you run a
    script that you did not write, treat the file as you would treat any
    unsigned script. Review the code to determine whether you can trust the
    script.

 ENABLE STRONG PRIVATE KEY PROTECTION FOR YOUR CERTIFICATE
 ---------------------------------------------------------

    If you have a private certificate on your computer, malicious
    programs might be able to sign scripts on your behalf, which
    authorizes Windows PowerShell to run them.

    To prevent automated signing on your behalf, use Certificate
    Manager (Certmgr.exe) to export your signing certificate to
    a .pfx file. Certificate Manager is included in the Microsoft
    .NET Framework SDK, the Microsoft Windows SDK, and in Internet
    Explorer 5.0 and later versions.

    To export the certificate:

        1. Start Certificate Manager.

        2. Select the certificate issued by PowerShell Local Certificate Root.

        3. Click Export to start the Certificate Export Wizard.

        4. Select "Yes, export the private key", and then click Next.

        5. Select "Enable strong protection."

        6. Type a password, and then type it again to confirm.

        7. Type a file name that has the .pfx file name extension.

        8. Click Finish.

    To re-import the certificate:

        1. Start Certificate Manager.

        2. Click Import to start the Certificate Import Wizard.

        3. Open to the location of the .pfx file that you created during the
           export process.

        4. On the Password page, select "Enable strong private key protection",
           and then enter the password that you assigned during the export
           process.

        5. Select the Personal certificate store.

        6. Click Finish.

 PREVENT THE SIGNATURE FROM EXPIRING
 -----------------------------------
     The digital signature in a script is valid until the signing certificate
     expires or as long as a time stamp server can verify that the script was
     signed while the signing certificate was valid.

     Because most signing certificates are valid for one year only, using a
     time stamp server ensures that users can use your script for many years
     to come.

SEE ALSO
    about_Execution_Policies
    about_Profiles
    Get-ExecutionPolicy
    Set-ExecutionPolicy
    Set-AuthenticodeSignature
    "Introduction to Code Signing" (http://go.microsoft.com/fwlink/?LinkId=106296)


about_Special_Characters

TOPIC
    about_Special_Characters

SHORT DESCRIPTION
    Describes the special characters that you can use to control how
    Windows PowerShell interprets the next character in a command or parameter.

LONG DESCRIPTION
    Windows PowerShell supports a set of special character sequences that
    are used to represent characters that are not part of the standard
    character set.

    The special characters in Windows PowerShell begin with the backtick
    character, also known as the grave accent (ASCII 96).

    The following special characters are recognized by Windows PowerShell:

        `0    Null
        `a    Alert
        `b    Backspace
        `f    Form feed
        `n    New line
        `r    Carriage return
        `t    Horizontal tab
        `v    Vertical tab

    These characters are case-sensitive.

NULL (`0)
    Windows PowerShell recognizes a null special character (`0) and represents
    it with a character code of 0. It appears as an empty space in the
    Windows PowerShell output. This allows you to use Windows PowerShell to
    read and process text files that use null characters, such as string
    termination or record termination indicators. The null special character
    is not equivalent to the $null variable, which stores a value of NULL.

ALERT (`a)
    The alert (`a) character sends a beep signal to the computer's speaker.
    You can use this to warn a user about an impending action. The following
    command sends two beep signals to the local computer's speaker:

        for ($i = 0; $i -le 1; $i++){"`a"}

BACKSPACE (`b)
    The backspace character (`b) moves the cursor back one character, but it
    does not delete any characters. The following command writes the word
    "backup", moves the cursor back twice, and then writes the word "out"
    (preceded by a space and starting at the new position):

        "backup`b`b out"

    The output from this command is as follows:

        back out

FORM FEED (`f)
   The form feed character (`f) is a print instruction that ejects the
   current page and continues printing on the next page. This character
   affects printed documents only; it does not affect screen output.

NEW LINE (`n)
    The new line character (`n) inserts a line break immediately after the
    character.

    The following example shows how to use the new line character in a
    Write-Host command:

        "There are two line breaks`n`nhere."

    The output from this command is as follows:

        There are two line breaks

        here.

CARRIAGE RETURN (`r)
    The carriage return character (`r) eliminates the entire line prior
    to the `r character, as though the prior text were on a different line.

    For example:

        Write-Host "Let's not move`rDelete everything before this point."

    The output from this command is:

        Delete everything before this point.

HORIZONTAL TAB (`t)
    The horizontal tab character (`t) advances to the next tab stop and
    continues writing at that point. By default, the Windows PowerShell
    console has a tab stop at every eighth space.

    For example, the following command inserts two tabs between each
    column.

        "Column1`t`tColumn2`t`tColumn3"

    The output from this command is:

        Column1         Column2         Column3

VERTICAL TAB (`v)
    The horizontal tab character (`t) advances to the next vertical tab stop
    and writes all subsequent output beginning at that point. This character
    affects printed documents only. It does not affect screen output.

SEE ALSO
    about_Quoting_Rules
    about_Escape_Characters


about_Split

TOPIC
    about_Split

SHORT DESCRIPTION
    Explains how to use the split operator to split one or more strings into
    substrings.

LONG DESCRIPTION
    The split operator splits one or more strings into substrings. You can
    change the following elements of the split operation:

    -- Delimiter. The default is whitespace, but you can specify characters,
           strings, patterns, or script blocks that specify the delimiter.

    -- Maximum number of substrings. The default is to return all substrings. If
           you specify a number less than the number of substrings, the remaining
           substrings are concatenated in the last substring.

    -- Options that specify the conditions under which the delimiter is matched,
           such as SimpleMatch and Multiline.

  SYNTAX

   The following diagram shows the syntax for the -split operator.

   The parameter names do not appear in the command. Include only the
   parameter values. The values must appear in the order specified in the
   syntax diagram.

    -Split <String>

    <String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]]

    <String> -Split {<ScriptBlock>} [,<Max-substrings>]

   In any split statement, you can substitute -iSplit or -cSplit for -split.
   The -iSplit and -split operators are case-insensitive. The -cSplit operator
   is case-sensitive, meaning that case is considered when the delimiter rules
   are applied.

  PARAMETERS

   <String>
        Specifies one or more strings to be split. If you submit multiple
        strings, all the strings are split using the same delimiter rules.
        Example:

        -split "red yellow blue green"
        red
            yellow
        blue
        green

   <Delimiter>
        The characters that identify the end of a substring. The default
        delimiter is whitespace, including spaces and non-printable characters, such
        as newline (`n) and tab (`t). When the strings are split, the delimiter
        is omitted from all the substrings. Example:

        "Lastname:FirstName:Address" -split ":"
        Lastname
        FirstName
        Address

    <Max-substrings>
        Specifies the maximum number of substrings returned. The default is
        all the substrings split by the delimiter. If there are more substrings,
        they are concatenated to the final substring. If there are fewer
        substrings, all the substrings are returned. A value of 0 and negative values return
        all the substrings.

        If you submit more than one string (an array of strings) to the split operator ,
        the Max-substrings limit is applied to each string separately. Example:

        $c = "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune"
        $c -split ",", 5
        Mercury
        Venus
        Earth
        Mars
        Jupiter,Saturn,Uranus,Neptune

    <ScriptBlock>
        An expression that specifies rules for applying the delimiter. The
        expression must evaluate to $true or $false. Enclose the script
        block in braces. Example:

            $c = "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune"
        $c -split {$_ -eq "e" -or $_ -eq "p"}
        M
        rcury,V
        nus,Earth,Mars,Ju
        it
        r,Saturn,Uranus,N

        tun

    <Options>
        Enclose the option name in quotation marks. Options are valid only
        when the <Max-substrings> parameter is used in the statement.

        The syntax for the Options parameter is:

        "SimpleMatch [,IgnoreCase]"

            "[RegexMatch] [,IgnoreCase] [,CultureInvariant]
            [,IgnorePatternWhitespace] [,ExplicitCapture]
            [,Singleline | ,Multiline]"

        The SimpleMatch options are:

          -- SimpleMatch: Use simple string comparison when evaluating the
             delimiter. Cannot be used with RegexMatch.

          -- IgnoreCase: Forces case-insensitive matching, even if the -cSplit
             operator is specified.

        The RegexMatch options are:

          -- RegexMatch: Use regular expression matching to evaluate the
             delimiter. This is the default behavior. Cannot be used with
             SimpleMatch.

          -- IgnoreCase: Forces case-insensitive matching, even if the -cSplit
             operator is specified.

          -- CultureInvariant: Ignores cultural differences in language
         when evaluting the delimiter. Valid only with RegexMatch.

          -- IgnorePatternWhitespace: Ignores unescaped whitespace and
             comments marked with the number sign (#). Valid only with
             RegexMatch.

          -- Multiline: Multiline mode recognizes the start and end of lines
             and strings. Valid only with RegexMatch. Singleline is the default.

          -- Singleline: Singleline mode recognizes only the start and end of
             strings. Valid only with RegexMatch. Singleline is the default.

          -- ExplicitCapture: Ignores non-named match groups so that only
         explicit capture groups are returned in the result list. Valid
             only with RegexMatch.

  UNARY and BINARY SPLIT OPERATORS

    The unary split operator (-split <string>) has higher precedence than a
    comma. As a result, if you submit a comma-separated list of strings to the
    unary split operator, only the first string (before the first comma) is
    split.

    To split more than one string, use the binary split operator
    (<string> -split <delimiter>). Enclose all the strings in parentheses,
    or store the strings in a variable, and then submit the variable to the
    split operator.

    Consider the following example:

    -split "1 2", "a b"
    1
    2
     a b

    "1 2", "a b" -split " "
    1
    2
     a
    b

    -split ("1 2", "a b")
    1
    2
     a
    b

    $a = "1 2", "a b"
    -split $a
    1
    2
     a
    b

  EXAMPLES

    The following statement splits the string at whitespace.

    C:\PS> -split "Windows PowerShell 2.0`nWindows PowerShell with remoting"

    Windows
    PowerShell
    2.0
    Windows
    PowerShell
    with
    remoting

    The following statement splits the string at any comma.

    C:\PS> "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split ','

        Mercury
        Venus
        Earth
        Mars
        Jupiter
        Saturn
        Uranus
        Neptune

    The following statement splits the string at the pattern "er".

    C:\PS>"Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split 'er'

    M
    cury,Venus,Earth,Mars,Jupit
    ,Saturn,Uranus,Neptune

    The following statement performs a case-sensitive split at the
    letter "N".

    C:\PS> "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -cSplit 'N'

    Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,
    eptune

    The following statement splits the string at "e" and "t".

        C:\PS> "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split '[et]'

        M
        rcury,V
        nus,
        ar
        h,Mars,Jupi

        r,Sa
        urn,Uranus,N
        p
        un

    The following statement splits the string at "e" and "r", but limits the
    resulting substrings to six substrings.

        C:\PS> "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split '[er]', 6

    M

    cu
    y,V
    nus,
    arth,Mars,Jupiter,Saturn,Uranus,Neptune

    The following statement splits a string into three substrings.

        C:\PS> "a,b,c,d,e,f,g,h" -split ",", 3

    a
    b
    c,d,e,f,g,h

    The following statement splits two strings into three substrings.
    (The limit is applied to each string independently.)

        C:\PS> "a,b,c,d", "e,f,g,h" -split ",", 3

    a
    b
    c,d
    e
    f
    g,h

    The following statement splits each line in the here-string at the
    first digit. It uses the Multiline option to recognize the beginning
    of each line and string.

    The 0 represents the "return all" value of the Max-substrings parameter. You can
    use options, such as Multiline, only when the Max-substrings value
    is specified.

        C:\PS> $a = @'
    1The first line.
    2The second line.
    3The third of three lines.
    '@

        C:\PS> $a -split "^\d", 0, "multiline"

    The first line.

    The second line.

    The third of three lines.

    The following statement uses the SimpleMatch option to direct the -split
    operator to interpret the dot (.) delimiter literally.

    With the default, RegexMatch, the dot enclosed in quotation marks (".") is
    interpreted to match any character except for a newline character. As a
    result, the split statement returns a blank line for every character except
    newline.

    The 0 represents the "return all" value of the Max-substrings parameter.
    You can use options, such as SimpleMatch, only when the Max-substrings
    value is specified.

        C:\PS> "This.is.a.test" -split ".", 0, "simplematch"

    This
        is
        a
    test

    The following statement splits the string at one of two delimiters,
    depending on the value of a variable.

        C:\PS> 	$i = 1
        C:\PS> 	$c = "LastName, FirstName; Address, City, State, Zip"
        C:\PS> 	$c -split {if ($i -lt 1) {$_ -eq ","} else {$_ -eq ";"}}

    LastName, FirstName
     Address, City, State, Zip

    The following split statements split an XML file first at the angle bracket
    and then at the semicolon. The result is a readable version of the XML
    file.

        C:\PS> 	get-process powershell | export-clixml ps.xml
        C:\PS> 	$x = import-clixml ps.xml
        C:\PS> 	$x = $x -split "<"
        C:\PS> 	$x = $x -split ";"

    To display the result, type "$x".

    C:\PS> $x

        @{__NounName=Process
    Name=powershell
    Handles=428
    VM=150081536
    WS=34840576
    PM=36253696
    ...

SEE ALSO
    Split-Path
    about_Operators
    about_Comparison_Operators
    about_Join


about_Switch

TOPIC
    about_Switch

SHORT DESCRIPTION
    Explains how to use a switch to handle multiple If statements.

LONG DESCRIPTION
    You use an If statement to make a decision in a script or program.
    Essentially, it says; “If this condition exists, perform this action.
    Otherwise do that action.” You can perform that operation as many
    times as you want, but if you have a long list of conditions, an If
    statement becomes unwieldy. You can combine a long list of conditions
    in a switch statement. As in all branching statements, braces ({})
    must enclose script blocks.

    A Switch statement is, in effect, a series of If statements. It matches
    the expression with each of the conditions case by case. If a match
    is found, the action associated with that condition is performed. A
    basic switch statement takes the following form:

        PS> $a = 3
        PS> switch ($a) {
            1 {"It is one."}
            2 {"It is two."}
            3 {"It is three."}
            4 {"It is four."}
            }

        It is three.

    This simple example takes a value and compares it with each condition
    in the list. The action echoes a string from the match. But, you
    could have a problem if you check all of the conditions.
    For example:

        PS> $day = "day5"
        PS> switch ($day){
            day1 {"Monday"; break}
            day2 {"Tuesday"; break}
            day3 {"Wednesday"; break}
            day4 {"Thursday"; break}
            day5 {"Friday"; break}
            day6 {"Saturday"; break}
            day7 {"Sunday"; break}
            day5 {"Too many days"; break}
            }

        Friday

    There are two day5 conditions in the list. But, the break at the end of
    each condition tells the switch to stop looking further and to perform
    the action it finds. If the break statements were not there, both
    day5 actions would be performed.

    If the value to switch against is an array, then each element in the
    array will be evaluated in order, starting at element 0 (zero). At least
    one element must be present that meets at least one condition; otherwise,
    an error will result. If there is more than one default clause, an
    error will result.

    The complete switch syntax is as follows:

        switch [-regex|-wildcard|-exact][-casesensitive] ( pipeline )

    or

        switch [-regex|-wildcard|-exact][-casesensitive] -file filename

    followed by

        {
            "string"|number|variable|{ expression } { statementlist }
            default { statementlist }
        }

    By default, if no parameters are used, Switch behaves as if a case-
    insensitive exact match is in effect. If "pipeline" results in an
    array, each element of the array will be evaluated in ascending offset
    order (starting at 0 [zero]).

    At least one conditional element must be present in the Switch
    codeblock, and only one default clause can be present. If more than
    one default clause is present, a ParseException will be thrown.

    Switch has the following parameters:

        Regex	        Indicates that the match clause, if it is a string, is
                        treated as a regex string. Use of this parameter
                        disables Wildcard and Exact. If the match clause is not
                        a string, this parameter is ignored.

        Wildcard	Indicates that the match clause, if it is a string, is
                        treated as a wildcard string. Use of this
                        parameter disables Regex and Exact. If the match clause
                        is not a string, this parameter is ignored.

        Exact	        Indicates that the match clause, if it is a string, must
                        match exactly. Use of this parameter disables
                        Wildcard and Regex. If the match clause is not a
                        string, this parameter is ignored.

        CaseSensitive	Modifies the match clause, if it is a string, to be
                        case-sensitive. If the match clause is not a string,
                        this parameter is ignored.

        File	        Takes input from a file (or representative) rather
                        than a statement. If multiple File parameters are
                        used, the last one is used. Each line of the
                        file is read and passed through the switch block.

    Multiple uses of Regex, Wildcard, or Exact are allowed. However, only
    the last parameter used governs the behavior.

    The Break keyword indicates that no more processing will occur and
    that the Switch statement will exit.

    The Continue keyword indicates that no processing will continue
    against the current token and that the next token in the conditional will
    be evaluated. If no tokens are available, the Switch statement will
    exit.

    The "{ expression }" block may be a code block that will be evaluated
    at the time of the comparison. The current object is bound to
    the $_ automatic variable and is available during the evaluation of
    the expression. A comparison is considered a match if the expression
    evaluates to "True".  This expression is evaluated in a new scope.

    The "Default" keyword within the switch statement indicates that if
    no matches are found, the code block that follows the keyword will
    be evaluated. Program flow will not be allowed from block to
    block because the closing brace ( } ) in the compound list is an explicit
    break.

    If multiple matches are found, each match results in the
    expression being executed. To avoid this, the Break or Continue
    keywords can be used to halt further comparisons.

SEE ALSO
    about_Break
    about_Continue
    about_If
    about_Script_Blocks


about_Throw

TOPIC
    about_Throw

SHORT DESCRIPTION
    Describes the Throw keyword, which generates a terminating error.

LONG DESCRIPTION
    The Throw keyword causes a terminating error. You can use the Throw keyword
    to stop the processing of a command, function, or script.

    For example, you can use the Throw keyword in the script block of an If
    statement to respond to a condition or in the Catch block of a
    Try-Catch-Finally statement. You can also use the Throw keyword in a
    parameter declaration to make a function parameter mandatory.

    The Throw keyword can throw any object, such as a user message string or
    the object that caused the error.

  SYNTAX

    The syntax of the Throw keyword is as follows:

        throw [<expression>]

    The expression in the Throw syntax is optional. When the Throw statement
    does not appear in a Catch block, and it does not include an expression,
    it generates a ScriptHalted error.

        C:\PS> throw

        ScriptHalted
        At line:1 char:6
        + throw <<<<
            + CategoryInfo          : OperationStopped: (:) [], RuntimeException
            + FullyQualifiedErrorId : ScriptHalted

    If the Throw keyword is used in a Catch block without an expression, it
    throws the current RuntimeException again. For more information, see
    about_Try_Catch_Finally.

  THROWING A STRING

    The optional expression in a Throw statement can be a string, as shown in
    the following example:

        C:\PS> throw "This is an error."

        This is an error.
        At line:1 char:6
        + throw <<<<  "This is an error."
            + CategoryInfo          : OperationStopped: (This is an error.:String) [], RuntimeException
            + FullyQualifiedErrorId : This is an error.

  THROWING OTHER OBJECTS

    The expression can also be an object that throws the object that represents
    the PowerShell process, as shown in the following example:

        C:\PS> throw (get-process powershell)

        System.Diagnostics.Process (powershell)
        At line:1 char:6
        + throw <<<<  (get-process powershell)
            + CategoryInfo          : OperationStopped: (System.Diagnostics.Process (powershell):Process) [],
                        RuntimeException
            + FullyQualifiedErrorId : System.Diagnostics.Process (powershell)

    You can use the TargetObject property of  the ErrorRecord object in the
    $error automatic variable to examine the error.

        C:\PS> $error[0].targetobject

        Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
        -------  ------    -----      ----- -----   ------     -- -----------
            319      26    61016      70864   568     3.28   5548 powershell

    You can also throw an ErrorRecord object or a Microsoft .NET Framework
    exception. The following example uses the Throw keyword to throw a
    System.FormatException object.

        C:\PS> $formatError = new-object system.formatexception

        C:\PS> throw $formatError

        One of the identified items was in an invalid format.
        At line:1 char:6
        + throw <<<<  $formatError
            + CategoryInfo          : OperationStopped: (:) [], FormatException
            + FullyQualifiedErrorId : One of the identified items was in an invalid format.

  RESULTING ERROR

    The Throw keyword can generate an ErrorRecord object. The Exception
    property of the ErrorRecord object contains a RuntimeException object.
    The remainder of the ErrorRecord object and the RuntimeException object
    vary with the object that the Throw keyword throws.

    The RunTimeException object is wrapped in an ErrorRecord object, and the
    ErrorRecord object is automatically saved in the $Error automatic variable.

  USING THROW TO CREATE A MANDATORY PARAMETER

    You can use the Throw keyword to make a function parameter mandatory.

    This is an alternative to using the Mandatory parameter of the Parameter
    keyword. When you use the Mandatory parameter, the system prompts the user
    for the required parameter value. When you use the Throw keyword, the
    command stops and displays the error record.

    For example, the Throw keyword in the parameter subexpression makes the
    Path parameter a required parameter in the function.

    In this case, the Throw keyword throws a message string, but it is the
    presence of the Throw keyword that generates the terminating error if
    the Path parameter is not specified. The expression that follows Throw
    is optional.

        function Get-XMLFiles
        {
            param ($path = $(throw "The Path parameter is required."))
            dir -path $path\* -include *.xml -recurse | sort lastwritetime | ft lastwritetime, attributes, name  -auto
        }

SEE ALSO
    about_Break
    about_Continue
    about_Scope
    about_Trap
    about_Try_Catch_Finally


about_Transactions

TOPIC
    about_Transactions

SHORT DESCRIPTION
    Describes how to manage transacted operations in Windows PowerShell.

LONG DESCRIPTION
    Transactions are supported in Windows PowerShell beginning
    in Windows PowerShell 2.0. This feature enables you to start
    a transaction, to indicate which commands are part of the
    transaction, and to commit or roll back a transaction.

  ABOUT TRANSACTIONS

      In Windows PowerShell, a transaction is a set of one or more
      commands that are managed as a logical unit. A transaction can
      be completed ("committed"), which changes data affected by the
      transaction. Or, a transaction can be completely undone ("rolled back")
      so that the affected data is not changed by the transaction.

      Because the commands in a transaction are managed as a unit,
      either all commands are committed, or all commands are rolled
      back.

      Transactions are widely used in data processing, most notably
      in database operations and for financial transactions. Transactions
      are most often used when the worst-case scenario for a set of
      commands is not that they all fail, but that some commands succeed
      while others fail, leaving the system in a damaged, false, or
      uninterpretable state that is difficult to repair.

  TRANSACTION CMDLETS

      Windows PowerShell includes several cmdlets designed for managing
      transactions.

      Cmdlet                 Description
      --------------         ---------------------------------
      Start-Transaction      Starts a new transaction.

      Use-Transaction        Adds a command or expression to the
                             transaction. The command must use
                             transaction-enabled objects.

      Undo-Transaction       Rolls back the transaction so that
                             no data is changed by the transaction.

      Complete-Transaction   Commits the transaction. The data
                             affected by the transaction is changed.

      Get-Transaction        Gets information about the active
                             transaction.

      For a list of transaction cmdlets, type:

          get-command *transaction

      For detailed information about the cmdlets, type:

      get-help <cmdlet-name> -detailed

      For example:

      get-help use-transaction -detailed

  TRANSACTION-ENABLED ELEMENTS

      To participate in a transaction, both the cmdlet and the provider
      must support transactions. This feature is built in to the objects
      that are affected by the transaction.

      The Windows PowerShell Registry provider supports transactions
      in Windows Vista. The TransactedString object
      (Microsoft.PowerShell.Commands.Management.TransactedString) works
      with any operating system that runs Windows PowerShell.

      Other Windows PowerShell providers can support transactions. To
      find the Windows PowerShell providers in your session that support
      transactions, use the following command to find the "Transactions"
      value in the Capabilities property of providers:

      get-psprovider | where {$_.Capabilities -like "*transactions*"}

      For more information about a provider, see the Help for the provider.
      To get provider Help, type:

      get-help <provider-name>

      For example, to get Help for the Registry provider, type:

      get-help registry

  THE USETRANSACTION PARAMETER

      Cmdlets that can support transactions have a UseTransaction
      parameter. This parameter includes the command in the active
      transaction. You can use the full parameter name or its alias,
      "usetx".

      The parameter can be used only when the session contains an
      active transaction. If you enter a command with the UseTransaction
      parameter when there is no active transaction, the command fails.

      To find cmdlets with the UseTransaction parameter, type:

      get-help * -parameter UseTransaction

      In Windows PowerShell core, all of the cmdlets designed to work
      with Windows PowerShell providers support transactions. As a
      result, you can use the provider cmdlets to manage transactions.

      For more information about Windows PowerShell providers,
      see about_Providers.

  THE TRANSACTION OBJECT

      Transactions are represented in Windows PowerShell by a
      transaction object, System.Management.Automation.Transaction.

      The object has the following properties:

      RollbackPreference:
          Contains the rollback preference set for the current
          transaction. You can set the rollback preference when you
          use Start-Transaction to start the transaction.

          The rollback preference determines the conditions under
          which the transaction is rolled back automatically. Valid
          values are Error, TerminatingError, and Never. The default
          value is Error.

      Status:
         Contains the current status of the transaction. Valid
         values are Active, Committed, and RolledBack.

      SubscriberCount:
         Contains the number of subscribers to the transaction. A
         subscriber is added to a transaction when you start a
         transaction while another transaction is in progress. The
         subscriber count is decremented when a subscriber commits
         the transaction.

  ACTIVE TRANSACTIONS

      In Windows PowerShell, only one transaction is active at a
      time, and you can manage only the active transaction. Multiple
      transactions can be in progress in the same session at the same
      time, but only the most-recently started transaction is active.

      As a result, you cannot specify a particular transaction when
      using the transaction cmdlets. Commands always apply to the
      active transaction.

      This is most evident in the behavior of the Get-Transaction cmdlet.
      When you enter a Get-Transaction command, Get-Transaction always
      gets only one transaction object. This object is the object that
      represents the active transaction.

      To manage a different transaction, you must first finish the active
      transaction, either by committing it or rolling it back. When you
      do this, the previous transaction becomes active automatically.
      Transactions become active in the reverse of order of which they are
      started, so that the most recently started transaction is always
      active.

  SUBSCRIBERS AND INDEPENDENT TRANSACTIONS

      If you start a transaction while another transaction is in progress,
      by default, Windows PowerShell does not start a new transaction.
      Instead, it adds a "subscriber" to the current transaction.

      When a transaction has multiple subscribers, a single
      Undo-Transaction command at any point rolls back the entire
      transaction for all subscribers. However, to commit the transaction,
      you must enter a Complete-Transaction command for every subscriber.

      To find the number of subscribers to a transaction, check the
      SubscriberCount property of the transaction object. For example,
      the following command uses the Get-Transaction cmdlet to get
      the value of the SubscriberCount property of the active transaction:

          (Get-Transaction).SubscriberCount

      Adding a subscriber is the default behavior because most transactions
      that are started while another transaction is in progress are related
      to the original transaction. In the typical model, a script that
      contains a transaction calls a helper script that contains its own
      transaction. Because the transactions are related, they should be
      rolled back or committed as a unit.

      However, you can start a transaction that is independent of the
      current transaction by using the Independent parameter of the
      Start-Transaction cmdlet.

      When you start an independent transaction, Start-Transaction
      creates a new transaction object, and the new transaction becomes
      the active transaction. The independent transaction can be
      committed or rolled back without affecting the original transaction.

      When the independent transaction is finished (committed or rolled
      back), the original transaction becomes the active transaction
      again.

  CHANGING DATA

      When you use transactions to change data, the data that is affected
      by the transaction is not changed until you commit the transaction.
      However, the same data can be changed by commands that are not
      part of the transaction.

      Keep this in mind when you are using transactions to manage shared
      data. Typically, databases have mechanisms that lock the data while
      you are working on it, preventing other users, and other commands,
      scripts, and functions, from changing it.

      However, the lock is a feature of the database. It is not related
      to transactions. If you are working in a transaction-enabled
      file system or other data store, the data can be changed while
      the transaction is in progress.

EXAMPLES
    The examples in this section use the Windows PowerShell Registry
    provider and assume that you are familiar with it. For information
    about the Registry provider, type "get-help registry".

  EXAMPLE 1: COMMITTING A TRANSACTION

    To create a transaction, use the Start-Transaction cmdlet. The
    following command starts a transaction with the default settings.

     start-transaction

    To include commands in the transaction, use the UseTransaction
    parameter of the cmdlet. By default, commands are not included
    in the transaction,

    For example, the following command, which sets the current
    location in the Software key of the HKCU: drive, is not included
    in the transaction.

        cd hkcu:\Software

    The following command, which creates the MyCompany key, uses the
    UseTransaction parameter of the New-Item cmdlet to include the
    command in the active transaction.

        new-item MyCompany -UseTransaction

    The command returns an object that represents the new key, but
    because the command is part of the transaction, the registry
    is not yet changed.

        Hive: HKEY_CURRENT_USER\Software

        SKC  VC Name                           Property
        ---  -- ----                           --------
          0   0 MyCompany                      {}

    To commit the transaction, use the Complete-Transaction cmdlet.
    Because it always affects the active transaction, you cannot specify
    the transaction.

    complete-transaction

    As a result, the MyCompany key is added to the registry.

    dir m*

        Hive: HKEY_CURRENT_USER\software

        SKC  VC Name                           Property
        ---  -- ----                           --------
         83   1 Microsoft                      {(default)}
          0   0 MyCompany                      {}

  EXAMPLE 2: ROLLING BACK A TRANSACTION

    To create a transaction, use the Start-Transaction cmdlet. The
    following command starts a transaction with the default settings.

     start-transaction

    The following command, which creates the MyOtherCompany key, uses the
    UseTransaction parameter of the New-Item cmdlet to include the
    command in the active transaction.

        new-item MyOtherCompany -UseTransaction

    The command returns an object that represents the new key, but
    because the command is part of the transaction, the registry
    is not yet changed.

        Hive: HKEY_CURRENT_USER\Software

        SKC  VC Name                           Property
        ---  -- ----                           --------
          0   0 MyOtherCompany                 {}

    To roll back the transaction, use the Undo-Transaction cmdlet.
    Because it always affects the active transaction, you do not specify
    the transaction.

    Undo-transaction

    The result is that the MyOtherCompany key is not added to the registry.

    dir m*

        Hive: HKEY_CURRENT_USER\software

        SKC  VC Name                           Property
        ---  -- ----                           --------
         83   1 Microsoft                      {(default)}
          0   0 MyCompany                      {}

  EXAMPLE 3: PREVIEWING A TRANSACTION

    Typically, the commands used in a transaction change data. However,
    the commands that get data are useful in a transaction, too, because
    they get data inside of the transaction. This provides a preview of the
    changes that committing the transaction would cause.

    The following example shows how to use the Get-ChildItem command
    (the alias is "dir") to preview the changes in a transaction.

    The following command starts a transaction.

    start-transaction

    The following command uses the New-ItemProperty cmdlet to add the
    MyKey registry entry to the MyCompany key. The command uses the
    UseTransaction parameter to include the command in the transaction.

        new-itemproperty -path MyCompany -Name MyKey -value 123 -UseTransaction

    The command returns an object representing the new registry entry,
    but the registry entry is not changed.

        MyKey
        -----
        123

    To get the items that are currently in the registry, use a Get-ChildItem
    command ("dir") without the UseTransaction parameter. The following
    command gets items that begin with "M."

    dir m*

    The result shows that no entries have yet been added to the MyCompany key.

        Hive: HKEY_CURRENT_USER\Software

        SKC  VC Name                           Property
        ---  -- ----                           --------
        83   1 Microsoft                      {(default)}
         0   0 MyCompany                      {}

    To preview the effect of committing the transaction, enter a Get-ChildItem
    ("dir") command with the UseTransaction parameter. This command has a view
    of the data from within the transaction.

    dir m* -useTransaction

    The result shows that, if the transaction is committed, the MyKey entry
    will be added to the MyCompany key.

        Hive: HKEY_CURRENT_USER\Software

        SKC  VC Name                           Property
        ---  -- ----                           --------
        83   1 Microsoft                      {(default)}
         0   1 MyCompany                      {MyKey}

  EXAMPLE 4: COMBINING TRANSACTED AND NON-TRANSACTED COMMANDS

    You can enter non-transacted commands during a transaction. The
    non-transacted commands affect the data immediately, but they do
    not affect the transaction.

    The following command starts a transaction in the HKCU:\Software
    registry key.

    start-transaction

    The next three commands use the New-Item cmdlet to add keys to
    the registry. The first and third commands use the UseTransaction
    parameter to include the commands in the transaction. The second
    command omits the parameter. Because the second command is not
    included in the transaction, it is effective immediately.

        new-item MyCompany1 -UseTransaction

        new-item MyCompany2

        new-item MyCompany3 -UseTransaction

    To view the current state of the registry, use a Get-ChildItem ("dir")
    command without the UseTransaction parameter. This command gets items
    that begin with "M."

    dir m*

    The result shows that the MyCompany2 key is added to the registry, but
    the MyCompany1 and MyCompany3 keys, which are part of the transaction,
    are not added.

        Hive: HKEY_CURRENT_USER\Software

        SKC  VC Name                           Property
        ---  -- ----                           --------
        83   1 Microsoft                      {(default)}
        0    0 MyCompany2                     {}

    The following command commits the transaction.

        complete-transaction

    Now, the keys that were added as part of the transaction appear in the
    registry.

    dir m*

        Hive: HKEY_CURRENT_USER\Software

        SKC  VC Name                           Property
        ---  -- ----                           --------
        83   1 Microsoft                      {(default)}
        0    0 MyCompany1                     {}
        0    0 MyCompany2                     {}
        0    0 MyCompany3                     {}

  EXAMPLE 5: USING AUTOMATIC ROLLBACK

    When a command in a transaction generates an error
    of any kind, the transaction is automatically rolled
    back.

    This default behavior is designed for scripts that
    run transactions. Scripts are typically well tested
    and include error-handling logic, so errors are not
    expected and should terminate the transaction.

    The first command starts a transaction in the HKCU:\Software
    registry key.

    start-transaction

    The following command uses the New-Item cmdlet to
    add the MyCompany key to the registry. The command uses
    the UseTransaction parameter (the alias is "usetx") to include
    the command in the transaction.

    New-Item MyCompany -UseTX

    Because the MyCompany key already exists in the registry,
    the command fails, and the transaction is rolled back.

        New-Item : A key at this path already exists
        At line:1 char:9
        + new-item <<<<  MyCompany -usetx

    A Get-Transaction command confirms that the transaction
    has been rolled back and that the SubscriberCount is 0.

        RollbackPreference   SubscriberCount   Status
        ------------------   ---------------   ------
        Error                0                 RolledBack

  EXAMPLE 6: CHANGING THE ROLLBACK PREFERENCE

    If you want the transaction to be more error tolerant,
    you can use the RollbackPreference parameter of
    Start-Transaction to change the preference.

    The following command starts a transaction with a
    rollback preference of "Never".

         start-transaction -rollbackpreference Never

    In this case, when the command fails, the transaction
    is not automatically rolled back.

    New-Item MyCompany -UseTX

        New-Item : A key at this path already exists
        At line:1 char:9
        + new-item <<<<  MyCompany -usetx

    Because the transaction is still active, you can
    resubmit the command as part of the transaction.

    New-Item MyOtherCompany -UseTX

  EXAMPLE 7: USING THE USE-TRANSACTION CMDLET

    The Use-Transaction cmdlet enables you to do direct scripting
    against transaction-enabled Microsoft .NET Framework  objects.
    Use-Transaction takes a script block that can only contain commands
    and expressions that use transaction-enabled .NET Framework objects,
    such as instances of the
    Microsoft.PowerShell.Commands.Management.TransactedString class.

    The following command starts a transaction.

         start-transaction

    The following New-Object command creates an instance of the
    TransactedString class and saves it in the $t variable.

         $t = New-Object Microsoft.PowerShell.Commands.Management.TransactedString

    The following command uses the Append method of the TransactedString
    object to add text to the string. Because the command is not part
    of the transaction, the change is effective immediately.

     $t.append("Windows")

    The following command uses the same Append method to add text, but
    it adds the text as part of the transaction. The command is enclosed
    in braces, and it is set as the value of the ScriptBlock parameter of
    Use-Transaction. The UseTransaction parameter (UseTx) is required.

     use-transaction {$t.append(" PowerShell")} -usetx

    To see the current content of the transacted string in $t, use the
    ToString method of the TransactedString object.

     $t.tostring()

    The output shows that only the non-transacted changes are effective.

     Windows

    To see the current content of the transacted string in $t from within
    the transaction, embed the expression in a Use-Transaction command.

     use-transaction {$s.tostring()} -usetx

    The output shows the transaction view.

     Windows PowerShell

    The following command commits the transaction.

     complete-transaction

    To see the final string:

     $t.tostring()

     Windows PowerShell

  EXAMPLE 7: MANAGING MULTI-SUBSCRIBER TRANSACTIONS

    When you start a transaction while another transaction is in
    progress, Windows PowerShell does not create a second transaction
    by default. Instead, it adds a subscriber to the current
    transaction.

    This example shows how to view and manage a multi-subscriber
    transaction.

    Begin by starting a transaction in the HKCU:\Software key.

        start-transaction

    The following command uses the Get-Transaction command to
    get the active transaction.

    get-transaction

    The result shows the object that represents the active transaction.

        RollbackPreference   SubscriberCount   Status
        ------------------   ---------------   ------
        Error                1                 Active

    The following command adds the MyCompany key to the registry.
    The command  uses the UseTransaction parameter to include the
    command in the transaction.

        new-item MyCompany -UseTransaction

    The following command uses the Start-Transaction command to
    start a transaction. Although this command is typed at the command
    prompt, this scenario is more likely to happen when you run a
    script that contains a transaction.

        start-transaction

    A Get-Transaction command shows that the subscriber count on the
    transaction object is incremented. The value is now 2.

        RollbackPreference   SubscriberCount   Status
        ------------------   ---------------   ------
        Error                2                 Active

    The next command uses the New-ItemProperty cmdlet to add the
    MyKey registry entry to the MyCompany key. It uses the UseTransaction
    parameter to include the command in the transaction.

        new-itemproperty -path MyCompany -name MyKey -UseTransaction

    The MyCompany key does not exist in the registry, but this
    command succeeds because the two commands are part of the
    same transaction.

    The following command commits the transaction. If it rolled back
    the transaction, the transaction would be rolled back for all the
    subscribers.

    complete-transaction

    A Get-Transaction command shows that the subscriber count on the
    transaction object is 1, but the value of Status is still Active
    (not Committed).

        RollbackPreference   SubscriberCount   Status
        ------------------   ---------------   ------
        Error                1                 Active

    To finish committing the transaction, enter a second Complete-
    Transaction command. To commit a multi-subscriber transaction,
    you must enter one Complete-Transaction command for each
    Start-Transaction command.

         complete-transaction

    Another Get-Transaction command shows that the transaction
    has been committed.

        RollbackPreference   SubscriberCount   Status
        ------------------   ---------------   ------
        Error                0                 Committed

  EXAMPLE 8: MANAGING INDEPENDENT TRANSACTIONS

    When you start a transaction while another transaction is in
    progress, you can use the Independent parameter of Start-Transaction
    to make the new transaction independent of the original transaction.

    When you do, Start-Transaction creates a new transaction object
    and makes the new transaction the active transaction.

    Begin by starting a transaction in the HKCU:\Software key.

        start-transaction

    The following command uses the Get-Transaction command to
    get the active transaction.

    get-transaction

    The result shows the object that represents the active transaction.

        RollbackPreference   SubscriberCount   Status
        ------------------   ---------------   ------
        Error                1                 Active

    The following command adds the MyCompany registry key as part of
    the transaction. It uses the UseTransaction parameter (UseTx)
    to include the command in the active transaction.

    new-item MyCompany -use

    The following command starts a new transaction. The command uses
    the Independent parameter to indicate that this transaction
    is not a subscriber to the active transaction.

         start-transaction -independent

    When you create an independent transaction, the new (most-recently
    created) transaction becomes the active transaction. You can use
    a Get-Transaction command to get the active transaction.

    get-transaction

    Note that the SubscriberCount of the transaction is 1, indicating
    that there are no other subscribers and that the transaction is
    new.

        RollbackPreference   SubscriberCount   Status
        ------------------   ---------------   ------
        Error                1                 Active

    The new transaction must be finished (either committed or rolled
    back) before you can manage the original transaction.

    The following command adds the MyOtherCompany key to the registry.
    It uses the UseTransaction parameter (UseTx) to include the command
    in the active transaction.

        new-item MyOtherCompany -usetx

    Now, roll back the transaction. If there were a single
    transaction with two subscribers, rolling back the transaction
    would roll back the entire transaction for all the subscribers.

    However, because these transactions are independent, rolling
    back the newest transaction cancels the registry changes and
    makes the original transaction the active transaction.

        undo-transaction

    A Get-Transaction command confirms that the original
    transaction is still active in the session.

    get-transaction

        RollbackPreference   SubscriberCount   Status
        ------------------   ---------------   ------
        Error                1                 Active

    The following command commits the active transaction.

        complete-transaction

    A Get-ChildItem command shows that the registry has been
    changed.

    dir m*

        Hive: HKEY_CURRENT_USER\Software

        SKC  VC Name                           Property
        ---  -- ----                           --------
        83   1 Microsoft                      {(default)}
         0   0 MyCompany                      {}

SEE ALSO
    Start-Transaction
    Get-Transaction
    Complete-Transaction
    Undo-Transaction
    Use-Transaction
    Registry (provider)
    about_Providers
    Get-PSProvider
    Get-ChildItem


about_Trap

TOPIC
    about_Trap

SHORT DESCRIPTION
    Describes a keyword that handles a terminating error.

LONG DESCRIPTION
    A terminating error stops a statement from running. If Windows PowerShell
    does not handle a terminating error in some way, Windows PowerShell also
    stops running the function or script in the current pipeline. In other
    languages, such as C#, terminating errors are referred to as exceptions.

    The Trap keyword specifies a list of statements to run when a terminating
    error occurs. Trap statements handle the terminating errors and allow
    execution of the script or function to continue instead of stopping.

  Syntax

      The Trap statement has the following syntax:

          trap [[<error type>]] {<statement list>}

      The Trap statement includes a list of statements to run when a
      terminating error occurs. The Trap keyword can optionally specify an
      error type. An error type requires brackets.

      A script or command can have multiple Trap statements. Trap statements
      can appear anywhere in the script or command.

  Trapping All Terminating Errors

      When a terminating error occurs that is not handled in another way in a
      script or command, Windows PowerShell checks for a Trap statement that
      handles the error. If a Trap statement is present, Windows PowerShell
      continues running the script or command in the Trap statement.

      The following example is a very simple Trap statement:

          trap {"Error found."}

      This Trap statement traps any terminating error. The following example is
      a function that contains this Trap statement:

          function TrapTest {
              trap {"Error found."}
              nonsenseString
              }

      This function includes a nonsense string that causes an error. Running
      this function returns the following:

          C:\PS> TrapTest
          Error found.

      The following example includes a Trap statement that displays the error
      by using the $_ automatic variable:

          function TrapTest {
              trap {"Error found: $_"}
              nonsenseString
              }

      Running this version of the function returns the following:

          C:\PS> TrapTest
          Error found: The term 'nonsenseString' is not recognized as the name
          of a cmdlet, function, script file, or operable program. Check the
          spelling of the name, or if a path was included verify that the path
          is correct, and then try again.

      Trap statements can also be more complex. A Trap statement can include
      multiple conditions or function calls. It can log, test, or even run
      another program.

   Trapping Specified Terminating Errors

      The following example is a Trap statement that traps the
      CommandNotFoundException error type:

          trap [System.Management.Automation.CommandNotFoundException]
              {"Command error trapped"}

      When a function or script encounters a string that does not match a known
      command, this Trap statement displays the "Command error trapped" string.
      After running any statements in the Trap statement list, Windows
      PowerShell writes the error object to the error stream and then continues
      the script.

      Windows PowerShell uses the Microsoft .NET Framework exception types. The
      following example specifies the System.Exception error type:

          trap [System.Exception] {"An error trapped"}

      The CommandNotFoundException error type inherits from the
      System.Exception type. This statement traps an error that is created by
      an unknown command. It also traps other error types.

      You can have more than one Trap statement in a script. Each error can be
      trapped by only one Trap statement. If an error occurs, and more than one
      Trap statement is available, Windows PowerShell uses the Trap statement
      with the most specific error type that matches the error.

      The following script example contains an error. The script includes a
      general Trap statement that traps any terminating error and a specific
      Trap statement that specifies the CommandNotFoundException type.

          trap {"Other terminating error trapped" }
          trap [System.Management.Automation.CommandNotFoundException] {"Command error trapped"}
          nonsenseString

      Running this script produces the following result:

          Command  error trapped
          The term 'nonsenseString' is not recognized as the name of a cmdlet,
          function, script file, or operable program. Check the spelling of
          the name, or if a path was included verify that the path is correct,
          and then try again.
          At C:\PS>testScript1.ps1:3 char:19
          +     nonsenseString <<<<

      Because Windows PowerShell does not recognize "nonsenseString" as a
      cmdlet or other item, it returns a CommandNotFoundException error. This
      terminating error is trapped by the specific Trap statement.

      The following script example contains the same Trap statements with a
      different error:

          trap {"Other terminating error trapped" }
          trap [System.Management.Automation.CommandNotFoundException]
              {"Command error trapped"}
          1/$null

      Running this script produces the following result:

          Other terminating error trapped
          Attempted to divide by zero.
          At C:PS> errorX.ps1:3 char:7
          +     1/ <<<< $null

      The attempt to divide by zero does not create a CommandNotFoundException
      error. Instead, that error is trapped by the other Trap statement, which
      traps any terminating error.

  Trapping Errors and Scope

      If a terminating error occurs in the same scope as the Trap statement,
      after running the Trap statements, Windows PowerShell continues at the
      statement after the error. If the Trap statement is in a different scope
      from the error, execution continues at the next statement that is in the
      same scope as the Trap statement.

      For instance, if an error occurs in a function, and the Trap statement is
      in the function, the script continues at the next statement. For example,
      the following script contains an error and a Trap statement:

          function function1 {
              trap { "An error: " }
              NonsenseString
              "function1 was completed"
              }

      Later in the script, running the Function1 function produces the
      following result:

          function1
          An error:
          The term 'NonsenseString' is not recognized as the name of a cmdlet,
          function, script file, or operable program. Check the spelling of the
          name, or if a path was included verify that the path is correct, and
          then try again.
          At C:\PS>TestScript1.ps1:3 char:19
          +     NonsenseString <<<<

          function1 was completed

      The Trap statement in the function traps the error. After displaying the
      message, Windows PowerShell resumes running the function. Note that
      Function1 was completed.

      Compare this with the following example, which has the same error and
      Trap statement. In this example, the Trap statement occurs outside the
      function:

          function function2 {
              NonsenseString
              "function2 was completed"
              }

          trap { "An error: " }
              . . .
          function2

      Later in the script, running the Function2 function produces the
      following result:

          An error:
          The term 'NonsenseString' is not recognized as the name of a cmdlet,
          function, script file, or operable program. Check the spelling of the
          name, or if a path was included verify that the path is correct, and
          then try again.
          At C:\PS>TestScript2.ps1:4 char:19
          +     NonsenseString <<<<

      In this example, the "function2 was completed" command was not run.
      Although both terminating errors occur within a function, if the Trap
      statement is outside the function, Windows PowerShell does not go back
      into the function after the Trap statement runs.

  Using the Break and Continue Keywords

      You can use the Break and Continue keywords in a Trap statement to
      determine whether a script or command continues to run after a
      terminating error.

      If you include a Break statement in a Trap statement list, Windows
      PowerShell stops the function or script. The following sample function
      uses the Break keyword in a Trap statement:

          C:\PS> function break_example {
              trap {"Error trapped"; break;}
              1/$null
              "Function completed."
              }

          C:\PS> break_example
          Error trapped
          Attempted to divide by zero.
          At line:4 char:7

      Because the Trap statement included the Break keyword, the function does
      not continue to run, and the "Function completed" line is not run.

      If you include a Continue statement in a Trap statement, Windows
      PowerShell resumes after the statement that caused the error, just as it
      would without Break or Continue. With the Continue keyword, however,
      Windows PowerShell does not write an error to the error stream.

      The following sample function uses the Continue keyword in a Trap
      statement:

          C:\PS> function continue_example {
              trap {"Error trapped"; continue;}
              1/$null
              "Function completed."}

          C:\PS> continue_example
          Error trapped
          Function completed.

      The function resumes after the error is trapped, and the "Function
      completed" statement runs. No error is written to the error stream.

SEE ALSO
    about_Break
    about_Continue
    about_Throw
    about_Try_Catch_Finally
    about_Scopes
    about_Try_Catch_Finally


about_Try_Catch_Finally

TOPIC
    about_Try_Catch_Finally

SHORT DESCRIPTION
    Describes how to use the Try, Catch, and Finally blocks to handle
    terminating errors.

LONG DESCRIPTION
    Use Try, Catch, and Finally blocks to respond to or handle terminating
    errors in scripts. The Trap statement can also be used to handle
    terminating errors in scripts. For more information, see about_Trap.

    A terminating error stops a statement from running. If Windows PowerShell
    does not handle a terminating error in some way, Windows PowerShell also
    stops running the function or script using the current pipeline. In other
    languages, such as C#, terminating errors are referred to as exceptions.
    For more information about errors, see about_Errors.

    Use the Try block to define a section of a script in which you want Windows
    PowerShell to monitor for errors. When an error occurs within the Try
    block, the error is first saved to the $Error automatic variable. Windows
    PowerShell then searches for a Catch block to handle the error. If the Try
    statement does not have a  matching Catch block, Windows PowerShell
    continues to search for an appropriate Catch block or Trap statement in the
    parent scopes. After a Catch block is completed or if no appropriate Catch
    block or Trap statement is found, the Finally block is run. If the error
    cannot be handled, the error is written to the error stream.

    A Catch block can include commands for tracking the failure or for
    recovering the expected flow of the script. A Catch block can specify which
    error types it catches. A Try statement can include multiple Catch blocks
    for different kinds of errors.

    A Finally block can be used to free any resources that are no longer needed
    by your script.

    Try, Catch, and Finally resemble the Try, Catch, and Finally keywords used
    in the C# programming language.

  Syntax
      A Try statement contains a Try block, zero or more Catch blocks, and zero
      or one Finally block. A Try statement must have at least one Catch block
      or one Finally block.

      The following shows the Try block syntax:

          try {<statement list>}

      The Try keyword is followed by a statement list in braces. If a
      terminating error occurs while the statements in the statement list are
      being run, the script passes the error object from the Try block to an
      appropriate Catch block.

      The following shows the Catch block syntax:

          catch [[<error type>][]] {<statement list>}

      Error types appear in brackets. The outermost brackets indicate the
      element is optional.

      The Catch keyword is followed by an optional list of error type
      specifications and a statement list. If a terminating error occurs in the
      Try block, Windows PowerShell searches for an appropriate Catch block. If
      one is found, the statements in the Catch block are executed.

      The Catch block can specify one or more error types. An error type is a
      Microsoft .NET Framework exception or an exception that is derived from a
      .NET Framework exception. A Catch block handles errors of the specified
      .NET Framework exception class or of any class that derives from the
      specified class.

      If a Catch block specifies an error type, that Catch block handles that
      type of error. If a Catch block does not specify an error type, that
      Catch block handles any error encountered in the Try block. A Try
      statement can include multiple Catch blocks for the different specified
      error types.

      The following shows the Finally block syntax:

          finally {<statement list>}

      The Finally keyword is followed by a statement list that runs every time
      the script is run, even if the Try statement ran without error or an
      error was caught in a Catch statement.

      Note that pressing CTRL+C stops the pipeline. Objects that are sent to
      the pipeline will not be displayed as output. Therefore, if you include
      a statement to be displayed, such as "Finally block has run", it will not
      be displayed after you press CTRL+C, even if the Finally block ran.

  Catching Errors
      The following sample script shows a Try block with a Catch block:

          try { NonsenseString }
          catch { "An error occurred." }

      The Catch keyword must immediately follow the Try block or another Catch
      block.

      Windows PowerShell does not recognize "NonsenseString" as a cmdlet or
      other item. Running this script returns the following result:

          An error occurred.

      When the script encounters "NonsenseString", it causes a terminating
      error. The Catch block handles the error by running the statement list
      inside the block.

  Using Multiple Catch Statements
      A Try statement can have any number of Catch blocks. For example, the
      following script has a Try block that downloads MyFile.doc, and it
      contains two Catch blocks:

          try
          {
             $wc = new-object System.Net.WebClient
             $wc.DownloadFile("http://www.contoso.com/MyDoc.doc")
          }
          catch [System.Net.WebException],[System.IO.IOException]
          {
              "Unable to download MyDoc.doc from http://www.contoso.com."
          }
          catch
          {
              "An error occurred that could not be resolved."
          }

      The first Catch block handles errors of the System.Net.WebException and
      System.IO.IOException types. The second Catch block does not specify an
      error type. The second Catch block handles any other terminating errors
      that occur.

      Windows PowerShell matches error types by inheritance. A Catch block
      handles errors of the specified .NET Framework exception class or of any
      class that derives from the specified class. The following example
      contains a Catch block that catches a "Command Not Found" error:

          catch [System.Management.Automation.CommandNotFoundException]
              {"Inherited Exception" }

      The specified error type, CommandNotFoundException, inherits from the
      System.SystemException type. The following example also catches a Command
      Not Found error:

          catch [System.SystemException] {"Base Exception" }

      This Catch block handles the "Command Not Found" error and other errors
      that inherit from the SystemException type.

      If you specify an error class and one of its derived classes, place the
      Catch block for the derived class before the Catch block for the general
      class.

  Freeing Resources by Using Finally
      To free resources used by a script, add a Finally block after the Try and
      Catch blocks. The Finally block statements run regardless of whether the
      Try block encounters a terminating error. Windows PowerShell runs the
      Finally block before the script terminates or before the current block
      goes out of scope.

      A Finally block runs even if you use CTRL+C to stop the script. A Finally
      block also runs if an Exit keyword stops the script from within a Catch
      block.

SEE ALSO
    about_Errors
    about_Trap


about_Type_Operators

TOPIC
    about_Type_Operators

SHORT DESCRIPTION
    Describes the operators that work with Microsoft .NET Framework types.

LONG DESCRIPTION
    The Boolean type operators (-is and -isnot) tell whether an object is an
    instance of a specified .NET Framework type. The -is operator returns a
    value of TRUE if the type matches and a value of FALSE otherwise.
    The -isnot operator returns a value of FALSE if the type
    matches and a value of TRUE otherwise.

    The -as operator tries to convert the input object to the specified .NET
    Framework type. If it succeeds, it returns the converted object. It if
    fails, it returns nothing. It does not return an error.

    The following table lists the type operators in Windows PowerShell.

    Operator  Description                 Example
    --------  ------------------------    -------------------------------------
    -is       Returns TRUE when the       C:\PS> (get-date) -is [datetime]
              input is an instance        True
              of the specified
              .NET Framework type.

    -isnot    Returns TRUE when the       C:\PS> (get-date) -isnot [datetime]
              input is not an instance    False
              of the specified
              .NETFramework type.

    -as       Converts the input to       C:\PS> 12/31/07 -as [datetime]
              the specified               Monday, December 31, 2007 12:00:00 AM
              .NET Framework type.

    The syntax of the type operators is as follows:

        <input> <operator> [.NET type]

    You can also use the following syntax:

        <input> <operator> ".NET type"

    To specify the .NET Framework type, enclose the type name in
    brackets ([ ]), or enter the type as a string, such as [DateTime] or
    "datetime" for System.DateTime. If the type is not at the root of the
    system namespace, specify the full name of the object type. You can omit
    "System.". For example, to specify System.Diagnostics.Process, enter
    [System.Diagnostics.Process], [Diagnostics.Process], or
    "diagnostics.process".

    The type operators always return a Boolean value, even if the input is a
    collection of objects. However, when the input is a collection, the type
    operators match the .NET Framework type of the collection. They do not
    match the type of each object, even when all of the objects are of the
    same type.

    To find the .NET Framework type of an object, use the Get-Member cmdlet.
    Or, use the GetType method of all the objects together with the FullName
    property of this method. For example, the following statement gets the
    type of the return value of a Get-Culture command:

        C:\PS> (get-culture).gettype().fullname
        System.Globalization.CultureInfo

EXAMPLES
    The following examples show some uses of the Type operators:

        C:\PS> 32 -is [Float]
        False

        C:\PS> 32 -is "int"
        True

        C:\PS> (get-date) -is [DateTime]
        True

        C:\PS> "12/31/2007" -is [DateTime]
        False

        C:\PS> "12/31/2007" -is [String]
        True

        C:\PS> (get-process powershell)[0] -is [System.Diagnostics.Process]
        True

        C:\PS> (get-command get-member) -is [System.Management.Automation.CmdletInfo]
        True

    The following example shows that when the input is a collection of objects,
    the matching type is the .NET Framework type of the collection, not the type
    of the individual objects in the collection.

    In this example, although both the Get-Culture and Get-UICulture cmdlets
    return System.Globalization.CultureInfo objects, a collection of these
    objects is a System.Object array.

        C:\PS> (get-culture) -is [System.Globalization.CultureInfo]
        True

        C:\PS> (get-uiculture) -is [System.Globalization.CultureInfo]
        True

        C:\PS> (get-culture), (get-uiculture) -is [System.Globalization.CultureInfo]
        False

        C:\PS> (get-culture), (get-uiculture) -is [Array]
        True

        C:\PS> (get-culture), (get-uiculture) | foreach {$_ -is [System.Globalization.CultureInfo])
        True
        True

        C:\PS> (get-culture), (get-uiculture) -is [Object]
        True

    The following examples show how to use the -as operator.

        C:\PS> "12/31/07" -is [datetime]
        False

        C:\PS> "12/31/07" -as [datetime]
        Monday, December 31, 2007 12:00:00 AM

        C:\PS> $date = "12/31/07" -as [datetime]

        C:\PS>$a -is [datetime]
        True

        C:\PS> 1031 -as [System.Globalization.CultureInfo]

        LCID             Name             DisplayName
        ----             ----             -----------
        1031             de-DE            German (Germany)

    The following example shows that when the -as operator cannot convert the
    input object to the .NET Framework type, it returns nothing.

        C:\PS> 1031 -as [System.Diagnostic.Process]
        C:\PS>

SEE ALSO
    about_Operators


about_Types.ps1xml

TOPIC
    about_Types.ps1xml

SHORT DESCRIPTION
    Explains how the Types.ps1xml files let you extend the Microsoft .NET
    Framework types of the objects that are used in Windows PowerShell.

LONG DESCRIPTION
    The Types.ps1xml file in the Windows PowerShell installation directory
    ($pshome) is an XML-based text file that lets you add properties and
    methods to the objects that are used in Windows PowerShell. Windows
    PowerShell has a built-in Types.ps1xml file that adds several elements
    to the .NET Framework types, but you can create additional Types.ps1xml
    files to further extend the types.

    For example, by default, array objects (System.Array) have a Length
    property that lists the number of objects in the array. However, because
    the name "length" does not clearly describe the property, Windows
    PowerShell adds an alias property named "Count" that displays the same
    value. The following XML adds the Count property to the System.Array type.

        <Type>
            <Name>System.Array</Name>
            <Members>
                <AliasProperty>
                    <Name>Count</Name>
                    <ReferencedMemberName>
                        Length
                    </ReferencedMemberName>
                </AliasProperty>
            </Members>
        </Type>

    To get the new AliasProperty, use a Get-Member command on any array, as shown
    in the following example.

        Get-Member -inputobject (1,2,3,4)

    The command returns the following results.

    Name           MemberType    Definition
    ----           ----------    ----------
    Count          AliasProperty Count = Length
    Address        Method        System.Object& Address(Int32 )
    Clone          Method        System.Object Clone()
    CopyTo         Method        System.Void CopyTo(Array array, Int32 index):
    Equals         Method        System.Boolean Equals(Object obj)
    Get            Method        System.Object Get(Int32 )
    ...

    As a result, you can use either the Count property or the Length property
    of arrays in Windows PowerShell. For example:

    C:\PS> (1, 2, 3, 4).count
    4

    C:\PS> (1, 2, 3, 4).length
    4

  Creating New Types.ps1xml Files

      The .ps1xml files that are installed with Windows PowerShell are
      digitally signed to prevent tampering because the formatting can include
      script blocks. Therefore, to add a property or method to a .NET Framework
      type, create your own Types.ps1xml files, and then add them to your
      Windows PowerShell console.

      To create a new file, start by copying an existing Types.ps1xml file. The
      new file can have any name, but it must have a .ps1xml file name
      extension. You can place the new file in any directory that is accessible
      to Windows PowerShell, but it is useful to place the files in the Windows
      PowerShell installation directory ($pshome) or in a subdirectory of the
      installation directory.

      When you have saved the new file, use the Update-TypeData cmdlet to add
      the new file to your Windows PowerShell console. If you want your types
      to take precedence over the types that are defined in the built-in file,
      use the PrependData parameter of the Update-TypeData cmdlet.
      Update-TypeData affects only the current console. To make the change to
      all future consoles, export the console, or add the Update-TypeData
      command to your Windows PowerShell profile.

  Types.ps1xml and Add-Member

      The Types.ps1xml files add properties and methods to all the instances
      of the objects of the specified .NET Framework type in the affected
      Windows PowerShell console. However, if you need to add properties or
      methods only to one instance of an object, use the Add-Member cmdlet.

      For more information,see Add-Member.

  Example: Adding an Age Member to FileInfo Objects

      This example shows how to add an Age property to file objects
      (System.IO.FileInfo). The age of a file is the difference between
      its creation time and the current time in days.

      It is easiest to use the original Types.ps1xml file as a template
      for the new file. The following command copies the original file to
      a file called MyTypes.ps1xml in the $pshome directory.

          copy-item Types.ps1xml MyTypes.ps1xml

      Next, open the Types.ps1xml file in any XML or text editor, such
      as Notepad. Because the Age property is calculated by using a script
      block, find a <ScriptProperty> tag to use as a model for the new Age
      property.

      Copy the XML between the <Type> and </Type> tags of the code to create
      the script property. Then, delete the remainder of the file, except for
      the opening <?xml> and <Types> tags and the closing </Types> tag. You
      must also delete the digital signature to prevent errors.

      Begin with the model script property, such as the following script
      property, which was copied from the original Types.ps1xml file.

          <?xml version="1.0" encoding="utf-8" ?>
          <Types>
              <Type>
                 <Name>System.Guid</Name>
                    <Members>
                        <ScriptProperty>
                            <Name>Guid</Name>
                            <GetScriptBlock>$this.ToString()</GetScriptBlock>
                        </ScriptProperty>
                    </Members>
              </Type>
          </Types>

      Then, change the name of the .NET Framework type, the name of the
      property, and the value of the script block to create an Age property
      for file objects.

          <?xml version="1.0" encoding="utf-8" ?>
          <Types>
              <Type>
                 <Name>System.IO.FileInfo</Name>
                    <Members>
                        <ScriptProperty>
                            <Name>Age</Name>
                            <GetScriptBlock>
                               ((get-date) - ($this.creationtime)).days
                            </GetScriptBlock>
                        </ScriptProperty>
                    </Members>
              </Type>
          </Types>

      After you save the file and close it, use an Update-TypeData command,
      such as the following command, to add the new Types.ps1xml file to the
      current console. The command uses the PrependData parameter to place the
      new file in a higher precedence order than the original file. (For more
      information about Update-TypeData, see Update-TypeData.)

          update-typedata -prependpath $pshome\MyTypes.ps1xml

      To test the change, use a Get-ChildItem command to get the
      PowerShell.exe file in the $pshome directory, and then pipe the file to
      the Format-List cmdlet to list all of the properties of the file. As a
      result of the change, the Age property appears in the list.

        get-childitem $pshome\powershell.exe | format-list -property *

        PSPath            : Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS...
        PSParentPath      : Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS...
        PSChildName       : powershell.exe
        PSDrive           : C
        PSProvider        : Microsoft.PowerShell.Core\FileSystem
        PSIsContainer     : False
        Age               : 16
        VersionInfo       : File:             C:\WINDOWS\system32\WindowsPow...
                    InternalName:     POWERSHELL
                    OriginalFilename: PowerShell.EXE
    ...

      You can also display the Age property of the file by using the following
      command.

      (get-childitem $pshome\powershell.exe).age
          16

  The XML in Types.ps1xml Files

      The <Types> tag encloses all of the types that are defined in the file.
      There should be only one pair of <Types> tags.

      Each .NET Framework type mentioned in the file should be represented by
      a pair of <Type> tags.

      The type tags must contain the following tags:

          <Name>: A pair of <Name> tags that enclose the name of the affected
                  .NET Framework type.

          <Members>: A pair of <Members> tags that enclose the tags for the
                     new properties and methods that are defined for the
                     .NET Framework type.

      Any of the following member tags can be inside the <Members> tags.

      <AliasProperty>: Defines a new name for an existing property.

         The <AliasProperty> tag must have a pair of <Name> tags that specify
         the name of the new property and a pair of <ReferencedMemberName> tags
         that specify the existing property.

         For example, the Count alias property is an alias for the Length
         property of array objects.

             <Type>
                 <Name>System.Array</Name>
                 <Members>
                     <AliasProperty>
                         <Name>Count</Name>
                         <ReferencedMemberName>Length</ReferencedMemberName>
                     </AliasProperty>
                 </Members>
             </Type>

      <CodeMethod>:  References a static method of a .NET Framework class.

         The <CodeMethod> tag must have a pair of <Name> tags that specify
         the name of the new method and a pair of <GetCodeReference> tags
         that specify the code in which the method is defined.

         For example, the Mode property of directories (System.IO.DirectoryInfo
         objects) is a code property defined in the Windows PowerShell
         FileSystem provider.

             <Type>
                 <Name>System.IO.DirectoryInfo</Name>
                 <Members>
                     <CodeProperty>
                        <Name>Mode</Name>
                        <GetCodeReference>
                           <TypeName>Microsoft.PowerShell.Commands.FileSystemProvider</TypeName>
                           <MethodName>Mode</MethodName>
                        </GetCodeReference>
                     </CodeProperty>
                 </Members>
             </Type>

      <CodeProperty>: References a static method of a .NET Framework class.

         The <CodeProperty> tag must have a pair of <Name> tags that specify
         the name of the new property and a pair of <GetCodeReference> tags
         that specify the code in which the property is defined.

         For example, the Mode property of directories (System.IO.DirectoryInfo
         objects) is a code property defined in the Windows PowerShell
         FileSystem provider.

             <Type>
                 <Name>System.IO.DirectoryInfo</Name>
                 <Members>
                     <CodeProperty>
                        <Name>Mode</Name>
                        <GetCodeReference>
                           <TypeName>Microsoft.PowerShell.Commands.FileSystemProvider</TypeName>
                           <MethodName>Mode</MethodName>
                        </GetCodeReference>
                     </CodeProperty>
                 </Members>
             </Type>

      <MemberSet>: Defines a collection of members (properties and methods).

         The <MemberSet> tags appear within the primary <Members> tags. The
         tags must enclose a pair of <Name> tags surrounding the name of the
         member set and a pair of secondary <Members> tags that surround the
         members (properties and methods) in the set. Any of the tags that
         create a property (such as <NoteProperty> or <ScriptProperty>) or a
         method (such as <Method> or <ScriptMethod>) can be members of the set.

         In Types.ps1xml files, the <MemberSet> tag is used to define the
         default views of the .NET Framework objects in Windows PowerShell. In
         this case, the name of the member set (the value within the <Name>
         tags) is always "PsStandardMembers", and the names of the properties
         (the value of the <Name> tag) are one of the following:

        - DefaultDisplayProperty: A single property of an object.

            - DefaultDisplayPropertySet: One or more properties of an object.

            - DefaultKeyPropertySet: One or more key properties of an object.
              A key property identifies instances of property values, such as
              the ID number of items in a session history.

         For example, the following XML defines the default display of services
         (System.ServiceProcess.ServiceController objects) that are returned by
         the Get-Service cmdlet. It defines a member set named
         "PsStandardMembers" that consists of a default property set with the
         Status, Name, and DisplayName properties.

             <Type>
                <Name>System.ServiceProcess.ServiceController</Name>
                <Members>
                   <MemberSet>
                       <Name>PSStandardMembers</Name>
                       <Members>
                           <PropertySet>
                             <Name>DefaultDisplayPropertySet</Name>
                             <ReferencedProperties>
                                <Name>Status</Name>
                                <Name>Name</Name>
                                <Name>DisplayName</Name>
                             </ReferencedProperties>
                           </PropertySet>
                       </Members>
                   </MemberSet>
                </Members>
             </Type>

      <Method>: References a native method of the underlying object.

      <Methods>: A collection of the methods of the object.

      <NoteProperty>: Defines a property with a static value.

         The <NoteProperty> tag must have a pair of <Name> tags that specify
         the name of the new property and a pair of <Value> tags that specify
         the value of the property.

         For example, the following XML creates a Status property for
         directories (System.IO.DirectoryInfo objects). The value of the
         Status property is always "Success".

             <Type>
                 <Name>System.IO.DirectoryInfo</Name>
                 <Members>
                     <NoteProperty>
                        <Name>Status</Name>
                    <Value>Success</Value>
                     </NoteProperty>
                 </Members>
             </Type>

      <ParameterizedProperty>: Properties that take arguments and return a
                               value.

      <Properties>: A collection of the properties of the object.

      <Property>: A property of the base object.

      <PropertySet>: Defines a collection of properties of the object.

         The <PropertySet> tag must have a pair of <Name> tags that specify
         the name of the property set and a pair of <ReferencedProperty> tags
         that specify the properties. The names of the properties are enclosed
         in <Name> tag pairs.

         In Types.ps1xml, <PropertySet> tags are used to define sets of
         properties for the default display of an object. You can identify the
         default displays by the value "PsStandardMembers" in the <Name> tag
         of a <MemberSet> tag.

         For example, the following XML creates a Status property for
         directories (System.IO.DirectoryInfo objects). The value of the Status
         property is always "Success".

             <Type>
                 <Name>System.ServiceProcess.ServiceController</Name>
                 <Members>
                     <MemberSet>
                         <Name>PSStandardMembers</Name>
                         <Members>
                             <PropertySet>
                                 <Name>DefaultDisplayPropertySet</Name>
                                 <ReferencedProperties>
                                     <Name>Status</Name
                                     <Name>Name</Name>
                                     <Name>DisplayName</Name>
                                 </ReferencedProperties>
                             </PropertySet>
                         <Members>
                     <MemberSet>
                 <Members>
             <Type>

     <ScriptMethod>: Defines a method whose value is the output of a script.

         The <ScriptMethod> tag must have a pair of <Name> tags that specify
         the name of the new method and a pair of <Script> tags that enclose
         the script block that returns the method result.

         For example, the ConvertToDateTime and ConvertFromDateTime methods of
         management objects (System.System.Management.ManagementObject) are
         script methods that use the ToDateTime and ToDmtfDateTime static
         methods of the System.Management.ManagementDateTimeConverter class.

             <Type>
                 <Name>System.Management.ManagementObject</Name>
                 <Members>
                     <ScriptMethod>
                         <Name>ConvertToDateTime</Name>
                         <Script>
                             [System.Management.ManagementDateTimeConverter]::ToDateTime($args[0])
                         </Script>
                     </ScriptMethod>
                     <ScriptMethod>
                         <Name>ConvertFromDateTime</Name>
                         <Script>
                             [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($args[0])
                         </Script>
                     </ScriptMethod>
                 </Members>
             </Type>

      <ScriptProperty>: Defines a property whose value is the output of a
                        script.

         The <ScriptProperty> tag must have a pair of <Name> tags that specify
         the name of the new property and a pair of <GetScriptBlock> tags
         that enclose the script block that returns the property value.

         For example, the VersionInfo property of files (System.IO.FileInfo
         objects) is a script property that results from using the FullName
         property of the GetVersionInfo static method of
         System.Diagnostics.FileVersionInfo objects.

             <Type>
                <Name>System.IO.FileInfo</Name>
                <Members>
                    <ScriptProperty>
                       <Name>VersionInfo</Name>
                       <GetScriptBlock>
                           [System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName)
                       </GetScriptBlock>
                    </ScriptProperty>
                </Members>
             </Type>

      For more information, see the Windows PowerShell Software Development
      Kit (SDK) in the MSDN (Microsoft Developer Network )library
      at http://go.microsoft.com/fwlink/?LinkId=144538.

  Update-TypeData

      To load your Types.ps1xml files into a Windows PowerShell console, use
      the Update-TypeData cmdlet. If you want the types in your file to take
      precedence over types in the built-in Types.ps1xml file, use the
      PrependData parameter of Update-TypeData. Update-TypeData affects only
      the current console. To make the change to all future consoles, export
      the console, or add the Update-TypeData command to your Windows
      PowerShell profile.

  Signing a Types.ps1xml File

      To protect users of your Types.ps1xml file, you can sign the file using
      a digital signature. For more information, see about_Signing.

SEE ALSO
    about_Signing
    Copy-Item
    Get-Member
    Update-TypeData


about_Variables

TOPIC
    about_Variables

SHORT DESCRIPTION
    Describes how variables store values that can be used in Windows
    PowerShell.

LONG DESCRIPTION
    A variable is a unit of memory in which values are stored. In Windows
    PowerShell, variables are represented by single-word text strings that
    begin with the dollar sign ($), such as $a, $process, or
    $my_var.

    There are several different types of variables in Windows PowerShell.

    -- User-created variables: User-created variables are created and
       maintained by the user. By default, the variables that you create at
       the Windows PowerShell command line exist only while the Windows
       PowerShell window is open, and they are lost when you close the window.
       To save a variable, add it to your Windows PowerShell profile. You can
       also create variables in scripts with global, script, or local scope.

    -- Automatic variables: Automatic variables store the state of
       Windows PowerShell. These variables are created by Windows PowerShell,
       and Windows PowerShell changes their values as required to maintain
       their accuracy. Users cannot change the value of these variables.
       For example, the $PSHome variable stores the path to the Windows
       PowerShell installation directory. For more information, a list, and
       a description of the automatic variables, see about_Automatic_Variables.

    -- Preference variables: Preference variables store user preferences for
       Windows PowerShell. These variables are created by Windows PowerShell
       and are populated with default values. Users can change the values of
       these variables. For example, MaximumHistoryCount determines the maximum
       number of entries in the session history. For more information, a list,
       and a description of the preference variables, see
       about_Preference_Variables.

 WORKING WITH VARIABLES

    To list all of the variables in your Windows PowerShell session, type:

       get-variable

    To display the value of any variable, type the name of the variable,
    preceded by a dollar sign ($). Windows PowerShell responds by displaying
    its value.

       $<variable-name>

    For example:

        PS> $pshome
        C:\Windows\System32\WindowsPowerShell\v1.0

    To create a new variable or to change the value of a variable, use an
    assignment statement in the following format:

        $<variable> = <value>

    For example:

        PS> $my-variable = 1, 2, 3

        or

        PS> $VerbosePreference = "Continue"

    To get an object that represents the variable, use a Get-Variable
    command, such as:

        PS> get-variable pid

    To use a variable, type the variable name, including the dollar sign ($),
    in a command or expression. If the command or expression is not enclosed
    in quotation marks or if it is enclosed in double-quotation marks ("), the
    value of the variable is used in the command or expression. If the command
    is enclosed in single quotation marks, ('), the variable name is used in
    the expression.

    For example, the first command finds the value of the $profile variable,
    which is the path to the Windows PowerShell user profile file. The
    second command opens the file in Notepad.

        PS> $profile
        C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

        PS> Notepad $profile

    You can store any type of object in a variable, including integers,
    strings, arrays, and hash tables, objects that represent processes,
    services, event logs, and computers.

  SAVING VARIABLES
      Variables that you create are available only in the session in which
      you create them. They are lost when you close your session.

      To save a variable, add the variable to your Windows PowerShell profile.
      Variables in a profile are added to every Windows PowerShell session
      that you open.

      For example, to change the value of the $VerbosePreference variable in
      every Windows PowerShell session, add the following command to your Windows
      PowerShell profile.

      $VerbosePreference = "Continue"

      You can add this command to your profile by opening the profile file in a
      text editor, such as Notepad, or you can use an Add-Content command, like
      the following one.

      The following command adds the new value for the $VerbosePreference variable
      to the CurrentUser,AllHosts profile.

      add-content -path $profile.CurrentUserAllHosts -value '$VerbosePreference = "Continue"'

      For more information about Windows PowerShell profiles, see about_profiles.

 VARIABLE NAMES WITH SPECIAL CHARACTERS

    You can use braces to force Windows PowerShell to interpret a
    variable name literally. This is especially helpful when creating
    or referring to a variable name that includes special characters,
    such as dashes, periods, colons, and parentheses.

    To create a variable name that includes a hyphen, enclose the
    variable name in braces. The following command creates a variable
    named "save-items".

        C:\PS> ${save-items} = "a", "b", "c"
        C:\PS>${save-items}
        a
        b
        c

    To refer to a variable name that includes parentheses, enclose
    the variable name in braces.

    For example, the following command gets the child items in the
    directory stores in the "ProgramFiles(x86)" environment variable.

        C:\PS> Get-childitem ${env:ProgramFiles(x86)}

    To refer to a variable name that includes braces, enclose the
    variable name in braces, and use the backtick (escape) character
    to escape the braces. For example, to create a variable
    named "this{value}is" with a value of 1, type:

        C:\PS> ${this`{value`}is} = 1
        C:\PS> ${this`{value`}is}
        1

 THE VARIABLE: DRIVE

     Windows PowerShell includes a Variable: drive that looks and acts like
     a file system drive, but it contains the variables in your session.

     To change to the variable drive, type:

        set-location variable:

         (or "cd variable:")

     When in the Variable drive, to list the items (variables) in the
     drive, use the Get-ChildItem cmdlet. For example:

         get-childitem

         (or "dir" or "ls")

     For more information about the Variable: drive and the Windows
     PowerShell Variable provider, type:

         get-help variable

SEE ALSO
    about_Automatic_Variables
    about_Environment_Variables
    about_Preference_Variables
    about_Scopes


about_While

TOPIC
    about_While

SHORT DESCRIPTION
    Describes a language statement that you can use to run a command block
    based on the results of a conditional test.

LONG DESCRIPTION
    The While statement (also known as a While loop) is a language construct
    for creating a loop that runs commands in a command block as long as a
    conditional test evaluates to true. The While statement is easier to
    construct than a For statement because its syntax is less complicated.
    In addition, it is more flexible than the Foreach statement because you
    specify a conditional test in the While statement to control how many times
    the loop runs.

    The following shows the While statement syntax:

        while (<condition>){<statement list>}

    When you run a While statement, Windows PowerShell evaluates
    the <condition> section of the statement before entering the
    <statement list> section. The condition portion of the statement resolves
    to either true or false. As long as the condition remains true, Windows
    PowerShell reruns the <statement list> section.

    The <statement list> section of the statement contains one or more commands
    that are run each time the loop is entered or repeated.

    For example, the following While statement displays the numbers 1
    through 3 if the $val variable has not been created or if the $val variable
    has been created and initialized to 0.

        while($val -ne 3)
        {
            $val++
            Write-Host $val
        }

    In this example, the condition ($val is not equal to 3) is true while
    $val = 0, 1, 2. Each time through the loop, $val is incremented by 1
    using the ++ unary increment operator ($val++). The last time through
    the loop, $val = 3. When $val equals 3, the condition statement
    evaluates to false, and the loop exits.

    To conveniently write this command at the Windows PowerShell command
    prompt, you can enter it in the following way:

        while($val -ne 3){$val++; Write-Host $val}

    Notice that the semicolon separates the first command that adds 1 to
    $val from the second command that writes the value of $val to the
    console.

SEE ALSO
    about_Comparison_Operators
    about_Foreach
    about_For


about_Wildcards

TOPIC
    about_Wildcards

SHORT DESCRIPTION
    Describes how to use wildcard characters in Windows PowerShell.

LONG DESCRIPTION
    In many cases, you will want to run a cmdlet against a group of
    items rather than an individual item. For example, you might
    want to locate all the files in the C:\Techdocs directory that have a
    .ppt file name extension. If you were to run the following command, it
    would return all the items in the directory:

        Get-ChildItem c:\techdocs

    The problem with this command is that you would have to visually
    inspect all the documents listed in the directory to determine which
    files use the .ppt file name extension. However, you can limit the items
    that are returned by using wildcard characters in a cmdlet's parameters.
    A wildcard character is a type of placeholder that allows you to search
    unknown values in order to return specific results. The process of using
    wildcard characters is sometimes referred to as "globbing". For example,
    you can recast the previous example so that only .ppt files are
    returned:

        Get-ChildItem c:\techdocs\*.ppt

    In this case, the asterisk (*) is used as a wildcard character to specify
    that any characters can exist before the .ppt file name extension. Because
    the file name extension is included, all files returned by the command must
    have that file name extension, but the files can have any name. As a
    result, only the files that you are looking for are returned.

    Windows PowerShell supports several wildcard characters in addition to the
    asterisk wildcard character.

        Wildcard Description        Example  Match             No match
        -------- ------------------ -------- ----------------- --------
        *        Matches zero or    a*       A, ag, Apple      banana
                 more characters

        ?        Matches exactly    ?n       an, in, on        ran
                 one character in
                 the specified
                 position

        [ ]      Matches a range    [a-l]ook book, cook, look  took
                 of characters

        [ ]      Matches specified  [bc]ook  book, cook        hook
                 characters

    Most cmdlets accept wildcard characters in some of their parameters. The
    Help topic for each cmdlet describes which parameters, if any, permit
    wildcard characters. For parameters in which wildcard characters are
    accepted, their use is case insensitive. For example, ?n will return An,
    an, In, in, On, and on.

    You can also mix wildcard characters within a single parameter. For
    example, suppose that you want to display all the .txt files in the
    C:\Techdocs directory that begin with the letters a through l. You can use
    the following command:

        Get-ChildItem c:\techdocs\[a-l]*.txt

    The command uses a range wildcard ([a-l]) to specify that the file name
    should begin with the letters a through l. The command then uses the
    asterisk wildcard character to provide a placeholder for any characters
    between the first letter and the file name extension.

SEE ALSO
    about_Language_Keywords


about_Windows_PowerShell_2.0

TOPIC
    about_Windows_PowerShell_2.0

SHORT DESCRIPTION
    Describes the new features that are included in Windows PowerShell 2.0.

LONG DESCRIPTION
    Windows PowerShell 2.0 includes several significant features that
    extend its use, improve its usability, and allow you to control and
    manage Windows-based environments more easily and comprehensively.

    Windows PowerShell 2.0 is backward compatible. Cmdlets, providers,
    snap-ins, scripts, functions, and profiles that were designed for Windows
    PowerShell 1.0 work in Windows PowerShell 2.0 without changes.

NEW FEATURES
    Windows PowerShell 2.0 includes the following new features.

  Remoting

      Windows PowerShell 2.0 lets you run commands on one or many remote
      computers with a single Windows PowerShell command. You can run
      individual commands, or you can create a persistent connection
      (a session) to run a series of related commands. You can also start a
      session with a remote computer so that the commands you type run
      directly on the remote computer.

      The remoting features of Windows PowerShell are built on Windows
      Remote Management (WinRM). WinRM is the Microsoft implementation of
      the WS-Management protocol, a standard SOAP-based, firewall-compatible
      communications protocol.

      The remote computers must have Windows PowerShell 2.0, the Microsoft .NET
      Framework 2.0, and the WinRM service. Remote commands are supported
      on all operating systems that can run Windows PowerShell. The
      current user must have permission to run commands on the remote
      computers. For more information, see about_Remote_Requirements.

      To support remoting, the Invoke-Command, Enter-PSSession, and
      Exit-PSSession cmdlets have been added, along with other cmdlets
      that contain the PSSession noun. These cmdlets let you create and manage
      persistent connections.

      The ComputerName parameter has also been added to several cmdlets,
      including the Get-Process, Get-Service, and Get-Eventlog cmdlets. This
      parameter allows you to get information about remote computers.
      These cmdlets use .NET Framework methods to get their data,
      so they do not rely on Windows PowerShell remoting. They do not require
      any new programs or configuration. For more information, see the Help for
      each cmdlet.

      For more information about remote commands, see about_Remote and
      about_Remote_FAQ. For more information about sessions, see
      about_PSSessions.

  Windows PowerShell ISE

      Windows PowerShell 2.0 includes Windows PowerShell Integrated
      Scripting Environment (ISE), a host application that lets you run
      commands, and design, write, test, and debug scripts in a graphical,
      color-coded, Unicode-based environment.

      Windows PowerShell ISE requires the Microsoft .NET Framework 3.0 or
      later.

      Windows PowerShell ISE includes:

      -  A Command pane that lets you run interactive commands just as you
         would in the Windows PowerShell console. Just type a command, and then
         press ENTER. The output appears in the Output pane.

      -  A Script pane that lets you compose, edit, debug, and run functions
         and scripts.

      -  Multiple tabs, each with its own Command and Script pane, that let you
         work on one or several tasks independently.

      Windows PowerShell ISE is designed for both novice and advanced users.

  Background Jobs

      Background jobs are commands that run asynchronously. When you run a
      background job, the command prompt returns immediately, even if the
      command is still running. You can use the background job feature to run a
      complex command in the background so that you can use your session for
      other work while the command runs.

      You can run a background job on a local or remote computer and then save
      the results on the local or remote computer. To run a job remotely, use
      the Invoke-Command cmdlet.

      Windows PowerShell includes a set of cmdlets that contain the Job noun
      (the Job cmdlets). Use these cmdlets for creating, starting, managing,
      and deleting background jobs and for getting the results of a background
      job. To get a list of the job cmdlets, type the following command:

          get-command *-job

      For more information about background jobs, see about_Jobs.

  Script Debugger

      Windows PowerShell 2.0 includes a cmdlet-based debugger for scripts and
      functions. The debugger is supported by a fully documented public API
      that you can use to build your own debugger or to customize or extend
      the debugger.

      The debugger cmdlets let you set breakpoints on lines, columns,
      variables, and commands. These cmdlets let you manage the breakpoints
      and display the call stack. You can create conditional breakpoints and
      specify custom actions at a breakpoint, such as running diagnostic and
      logging scripts.

      When you reach a breakpoint, Windows PowerShell suspends execution
      and starts the debugger. The debugger includes a set of custom commands
      that let you step through the code. You can also run standard Windows
      PowerShell commands to display the values of variables, and you can use
      cmdlets to investigate the results.

      For more information about debugging, see about_Debuggers.

  Data Section

      Scripts designed for Windows PowerShell 2.0 can have one or more
      DATA sections that isolate the data from the script logic. The data in
      the new DATA section is restricted to a specified subset of the Windows
      PowerShell scripting language.

      In Windows PowerShell 2.0, the DATA section is used to support
      script internationalization. You can use the DATA section to isolate
      and identify user message strings that will be translated into
      multiple user interface languages.

      For more information, see about_Data_Sections.

  Script Internationalization

      Windows PowerShell 2.0 script internationalization features allow you
      to better serve users throughout the world. Script internationalization
      enables scripts and functions to display messages and Help text to users
      in multiple languages.

      The script internationalization features query the operating system user
      interface culture ($PsUICulture) during execution and then import the
      appropriate translated text strings so you can display them to the user.
      The Data section lets you store text strings separate from code so that
      they are easily identified. A new cmdlet, ConvertFrom-StringData,
      converts text strings into dictionary-like hash tables to facilitate
      translation.

      For more information, see about_Script_Internationalization.

  WMI Cmdlets

      The Windows Management Instrumentation (WMI) functionality of
      Windows PowerShell 2.0 is improved with the addition of the following
      cmdlets:

          - Remove-WmiObject
          - Set-WmiInstance
          - Invoke-WmiMethod

      New parameters have been added to the Get-WmiObject cmdlet. All the WMI
      cmdlets now support the following parameters:

          - EnableAllPrivileges
          - Impersonation
          - Authentication
          - Authority

      These new parameters give you more refined control over the security
      configuration of your WMI operations without requiring you to work
      directly with the types in the .NET Framework Class Library.

      For a list of WMI cmdlets, type the following command:

          get-help *wmi*

      To get help for each cmdlet, type get-help followed by the cmdlet name.

  The Get-WinEvent Cmdlet

      The Get-WinEvent cmdlet gets events from Event Viewer logs and from
      Event Tracing for Windows (ETW) event log files on local and remote
      computers. It can get events from classic event logs and from the
      Windows Event Logs that were introduced in Windows Vista.

      You can use Get-WinEvent to get the objects that represent event logs, event
      log providers, and the events in the logs. Get-WinEvent lets you combine
      events from different sources in a single command. It supports
      advanced queries in XML Path Language (XPath), XML, and hash table
      format.

      Get-WinEvent requires Windows Vista or Windows Server 2008 and the
      Microsoft .NET Framework 3.5.

  The Out-Gridview Cmdlet

      The Out-GridView cmdlet displays the results of other commands in an
      interactive table in which you can search, sort, group, and filter the
      results. For example, you can send the results of a Get-Process,
      Get-WmiObject, Get-WinEvent, or Get-Eventlog command to Out-GridView and
      then use the table features to examine the data.

        help out-gridview -full

  The Add-Type Cmdlet

      The Add-Type cmdlet lets you add .NET Framework types to
      Windows PowerShell from the source code of another .NET Framework
      language.

      Add-Type compiles the source code that creates the types and generates
      assemblies that contain the new .NET Framework types. Then, you can use
      the .NET Framework types in Windows PowerShell commands along with the
      standard object types provided by the .NET Framework.

      You can also use Add-Type to load assemblies into your session so that
      you can use the types in the assemblies in Windows PowerShell.

      Add-Type allows you develop new .NET Framework types, to
      use .NET Framework types in C# libraries, and to access Win32 APIs.

      For more information, see Add-Type.

  Event Notification

      Windows PowerShell 2.0 introduces event notification. Users can register
      and subscribe to events, such as Windows PowerShell events, WMI events,
      or .NET Framework events. And, users can listen, forward, and act on
      management and system events both synchronously and asynchronously.

      Developers can write applications that use the event architecture
      to receive notification about state changes. Users can write
      scripts that subscribe to various events and that react to the content.

      Windows PowerShell provides cmdlets that create new events, get
      events and event subscriptions, register and unregister events,
      wait for events, and delete events. For more information about these
      cmdlets, type the following command:

          get-command *-event

  Modules

      Windows PowerShell modules let you divide and organize your
      Windows PowerShell scripts into independent, self-contained,
      reusable units. Code from a module executes in its own context,
      so it does not add to, conflict with, or overwrite the variables,
      functions, aliases, and other resources in the session.

      You can write, distribute, combine, share, and reuse modules to build
      simple scripts and complex applications.

      Windows PowerShell 2.0 includes cmdlets to add, get, and remove modules
      and to export module members. For more information about the cmdlets
      that are related to modules, type the following command:

          get-command *-module*

  Transactions

      Windows PowerShell 2.0 includes support for transactions. Transactions
      let you undo an entire series of operations. Transactions are available
      only for operations that support transactions. They are designed for
      applications that require atomicity, consistency, isolation, and
      recoverability, like databases and message queuing.

      Cmdlets and providers that support transactions have a new
      UseTransaction parameter. To start an operation within a transaction,
      use the Start-Transaction cmdlet. Then, when you use the cmdlets that
      perform the operation, use the UseTransaction parameter of each cmdlet
      when you want the command to be part of a transaction.

      If any command in the transaction fails at any point, use the
      Rollback-Transaction cmdlet to undo all the commands in the transaction.
      If all the commands succeed, use the Commit-Transaction cmdlet to make
      the command actions permanent.

      Windows PowerShell 2.0 includes cmdlets to start, use, commit, and roll
      back transactions. For information about these cmdlets, type the
      following command:

          get-command *transaction*

 Breaking Changes to Windows PowerShell 1.0

     -- The value of the PowerShellVersion registry entry in
        HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine
        is changed to 2.0.

     -- New cmdlets and variables have been added. These additions might
       conflict with variables and functions in profiles and scripts.

     -- The -IEQ operator performs a case insensitive comparison on characters.

     -- The Get-Command cmdlet gets functions by default, in addition to
        cmdlets.

     -- Native commands that generate a user interface cannot be piped to the
        Out-Host cmdlet.

     -- The new Begin, Process, End, and Dynamic Param language keywords might
        conflict with similar words used in scripts and functions. Interpreting
        these words as language keywords might result in parsing errors.

     -- Cmdlet name resolution has changed. In Windows PowerShell 1.0, a
        runtime error was generated when two Windows PowerShell snap-ins
        exported cmdlets with the same name. In Windows PowerShell 2.0, the
        last cmdlet that is added to the session runs when you type the command
        name. To run a command that does not run by default, qualify the cmdlet
        name with the name of the snap-in or module in which it originated.

     -- A function name followed by '-?' gets the help topic for the function,
        if one is included in the function.

    --  Parameter resolution for Microsoft .Net Frameword methods have changed.
        In Windows PowerShell 1.0, if you called an overloaded .NET method
        that has more than one best fit syntax, no error was reported. In
        Windows PowerShell 2.0, an ambiguity error is reported.

        In addition, in Windows PowerShell 2.0, the algorithm for choosing the
        best fit method has been revised significantly to minimize the number
        of ambiguities.

     -- If you are enumerating a collection in the pipeline and you try to
        modify the collection in the pipeline, Windows PowerShell throws an
        exception.

        For example, the following commands would work in Windows
        PowerShell 1.0, but would fail after first pipeline iteration in
        Windows PowerShel 2.0.

            $h = @{Name="Hello"; Value="Test"}
            $h.keys | foreach-object {$h.remove($_)}

        To avoid this error, create a sub-expression for the enumerator
        by using the $() characters. For example:

        $($h.keys) | foreach-object {$h.remove($_)}

    For more information about Windows PowerShell 2.0, visit the following Web
    sites:

    -- Windows PowerShell Web Site
       http://go.microsoft.com/fwlink/?LinkID=106031

    -- Windows PowerShell Team Blog:
       http://go.microsoft.com/fwlink/?LinkId=143696

SEE ALSO
    about_Data_Sections
    about_Debuggers
    about_Functions_Advanced
    about_Jobs
    about_Join
    about_PSSessions
    about_Remote
    about_Script_Internationalization
    about_Split


about_Windows_PowerShell_ISE

TOPIC
    about_Windows_PowerShell_ISE

SHORT DESCRIPTION
    Describes the features and system requirements of Windows PowerShell
    Integrated Scripting Environment (ISE).

LONG DESCRIPTION
    Windows PowerShell ISE is a host application for Windows PowerShell.
    In Windows PowerShell ISE, you can run commands and write, test, and debug
    scripts in a single Windows-based graphical user interface. Its features
    include multiline editing, tab completion, syntax coloring, selective
    execution, context-sensitive Help, and support for right-to-left languages.

    Notes: Because this feature requires a user interface, it does not work on
           Server Core installations of Windows Server.

           Window PowerShell ISE is built on the Windows Presentation
           Foundation (WPF). If the graphical elements of Windows PowerShell
           ISE do not render correctly on your system, you might resolve the
           problem by adding or adjusting the graphics rendering settings on
           your system. This might be required if the computer has an older
           video driver or you are using virtualization software. For more
           information, see "Graphics Rendering Registry Settings" in the MSDN
           library at http://go.microsoft.com/fwlink/?LinkId=144711.

 Running Interactive Commands

    You can run any Windows PowerShell expression or command in Windows
    PowerShell ISE. You can use cmdlets, providers, snap-ins, and modules as
    you would use them in the Windows PowerShell console.

    You can type or paste interactive commands in the Command pane. To run the
    commands, you can use buttons, menu items, and keyboard shortcuts.

    You can use the multiline editing feature to type or paste several lines
    of code into the Command pane at once. When you press the UP ARROW key to
    recall the previous command, all the lines in the command are recalled.
    When you type commands, press SHIFT+ENTER to make a new blank line appear
    under the current line.

 Viewing Output

    The results of commands and scripts are displayed in the Output pane. You
    can move or copy the results from the Output pane by using keyboard
    shortcuts or the Output toolbar, and you can paste the results in other
    programs. You can also clear the Output pane by clicking the Clear Output
    button or by typing one of the following commands:

        clear-host

        cls

 Writing Scripts and Functions

    In the Script pane, you can open, compose, edit, and run scripts. The
    Script pane lets you edit scripts by using buttons and keyboard shortcuts.
    You can also copy, cut, and paste text between the Script pane and the
    Command pane.

    You can use the selective run feature to run all or part of a script. To
    run part of a script, select the text you want to run, and then click the
    Run Script button. Or, press F5.

 Debugging Scripts

    You can use the Windows PowerShell ISE debugger to debug a Windows
    PowerShell script or function. When you debug a script, you can use menu
    items and shortcut keys to perform many of the same tasks that you would
    perform in the Windows PowerShell console. For example, to set a line
    breakpoint in a script, right-click the line of code, and then click
    Toggle Breakpoint.

    You can also use the Windows PowerShell debugger cmdlets in the Command
    pane just as you would use them in the console.

 Tab Completion

    Windows PowerShell ISE has tab completion for cmdlet names, parameter
    names, and Microsoft .NET Framework static types. To use tab completion,
    type the beginning of the name, and then press the TAB key.

 Getting Help

    Windows PowerShell ISE includes a searchable compiled Help file that
    describes Windows PowerShell ISE and Windows PowerShell. This Help file
    includes all the Help that is available from the Get-Help cmdlet. To view
    the Help file in Windows PowerShell ISE, use the Help menu. Or, press F1.

    The Help is context sensitive. For example, if you type Invoke-Item and
    then press F1, the Help file opens to the Help topic for the Invoke-Item
    cmdlet.

    And, you can use the Get-Help cmdlet in Windows PowerShell as you would in
    the Windows PowerShell console.

 Customizing the View

    You can use Windows PowerShell ISE features to move and to resize the
    Command pane, the Output pane, and the Script pane. You can show and hide
    the Script pane, and you can change the text size in all the panes.

    You can also use the $Host variable to change some aspects of the
    appearance of Windows PowerShell ISE, including the window title and the
    foreground and background colors in the Output pane. In addition, Windows
    PowerShell ISE has its own custom host variable, $psgHost. You can use
    this variable to customize Windows PowerShell ISE, including adding menus
    and menu items.

 Windows PowerShell ISE Profile

    Windows PowerShell ISE has its own Windows PowerShell profile,
    Microsoft.PowerShellISE_profile.ps1. In this profile, you can store
    functions, aliases, variables, and commands that you use in Windows
    PowerShell ISE.

    Items in the Windows PowerShell AllHosts profiles (CurrentUser\AllHosts
    and AllUsers\AllHosts) are also available in Windows PowerShell ISE, just
    as they are in any Windows PowerShell host program. However, the items
    in your Windows PowerShell console profiles are not available in Windows
    PowerShell ISE.

    Instructions for moving and reconfiguring your profiles are available in
    Windows PowerShell ISE Help and in about_Profiles.

 System Requirements

    -Operating Systems:
         - Windows 7
         - Windows Server 2008
         - Windows Server 2003 with Service Pack 2
         - Windows Vista with Service Pack 1
         - Windows XP with Service Pack 2

    - Microsoft .NET Framework 3.0

    - Windows PowerShell remoting requires Windows Remote Management 2.0.

 Notes

    - The Get-WinEvent cmdlet requires Windows Vista and later versions of
       Windows and the  Microsoft .NET Framework 3.5.

    - The Export-Counter cmdlet runs only in Windows 7.

 Starting Windows PowerShell ISE

    - To start Windows PowerShell ISE, click Start, point to All Programs,
      point to Windows PowerShell, and then click Windows PowerShell ISE.

    - In the Windows PowerShell console, Cmd.exe, or in the Run box,
      type "powershell_ise.exe".

SEE ALSO
    about_Profiles
    Get-Help


about_WMI_Cmdlets

TOPIC
    about_WMI_cmdlets

SHORT DESCRIPTION
    Provides background information about Windows Management Instrumentation
    (WMI) and Windows PowerShell.

LONG DESCRIPTION
    This topic provides information about WMI technology, the WMI cmdlets for
    Windows PowerShell, WMI-based remoting, WMI accelerators,
    and WMI troubleshooting. This topic also provides links to more information
    about WMI.

  About WMI

      Windows Management Instrumentation (WMI) is the Microsoft implementation
      of Web-Based Enterprise Management (WBEM), which is an industry
      initiative to develop a standard technology for accessing management
      information in an enterprise environment. WMI uses the Common Information
      Model (CIM) industry standard to represent systems, applications,
      networks, devices, and other managed components. CIM is developed and
      maintained by the Distributed Management Task Force (DMTF). You can use
      WMI to manage both local and remote computers. For example, you can use
      WMI to do the following:

          -- Start a process on a remote computer.

          -- Restart a computer remotely.

          -- Get a list of the applications that are installed on a local or
             remote computer.

          -- Query the Windows event logs on a local or remote computer.

  The WMI Cmdlets for Windows PowerShell

      Windows PowerShell implements WMI functionality through a set of cmdlets
      that are available in Windows PowerShell by default. You can use these
      cmdlets to complete the end-to-end tasks necessary to manage local and
      remote computers.

      The following WMI cmdlets are included.

      Cmdlet                 Description
      ------------------     ----------------------------------------------
      Get-WmiObject          Gets instances of WMI classes or information
                             about the available classes.

      Invoke-WmiMethod       Calls WMI methods.

      Register-WmiEvent      Subscribes to a WMI event.

      Remove-WmiObject       Deletes WMI classes and instances.

      Set-WmiInstance        Creates or modifies instances of WMI classes.

  Sample Commands

      The following command displays the BIOS information for the local
      computer.

          C:\PS> get-wmiobject win32_bios | format-list *

      The following command  displays information about the WinRM service
      for three remote computers.

          C:\PS> get-wmiobject -query "select * from win32_service where name='WinRM'" -computername server01, server01, server03

      The following more complex command exits all instances of a program.

          C:\PS> notepad.exe
          C:\PS> $np = get-wmiobject -query "select * from win32_process where name='notepad.exe'"
          C:\PS> $np | remove-wmiobject

  WMI-Based Remoting

      While the ability to manage a local system through WMI is useful, it is
      the remoting capabilities that make WMI a powerful administrative tool.
      WMI uses Microsoft's Distributed Component Object Model (DCOM) to
      connect to and manage systems. You might have to configure some systems
      to allow DCOM connections. Firewall settings and locked-down DCOM
      permissions can block WMI's ability to remotely manage systems.

  WMI Type Accelerators

      Windows PowerShell includes WMI type accelerators. These WMI type
      accelerators (shortcuts) allow more direct access to a WMI objects
      than a non-type accelerator approach would allow.

      The following type accelerators are supported with WMI:

          [WMISEARCHER] - A shortcut for searching for WMI objects.

          [WMICLASS] - A shortcut for accessing the static properties
                       and methods of a class.

          [WMI] - A shortcut for getting a single instance of a class.

      [WMISEARCHER] is a type accelerator for a ManagementObjectSearcher.
      It can take a string constructor to create a searcher that you can then
      do a GET() on.

      For example:

      PS> $s = [WmiSearcher]'Select * from Win32_Process where Handlecount > 1000'
      PS> $s.Get() |sort handlecount |ft handlecount,__path,name -auto

      handlecount  __PATH                                              name
      -----------  ------                                              ----
      1105         \\SERVER01\root\cimv2:Win32_Process.Handle="3724"   powershell...
      1132         \\SERVER01\root\cimv2:Win32_Process.Handle="1388"   winlogon.exe
      1495         \\SERVER01\root\cimv2:Win32_Process.Handle="2852"   iexplore.exe
      1699         \\SERVER01\root\cimv2:Win32_Process.Handle="1204"   OUTLOOK.EXE
      1719         \\SERVER01\root\cimv2:Win32_Process.Handle="1912"   iexplore.exe
      2579         \\SERVER01\root\cimv2:Win32_Process.Handle="1768"   svchost.exe

      [WMICLASS] is a type accelerator for ManagementClass. This has a
      string constructor that takes a local or absolute WMI path to a WMI
      class and returns an object that is bound to that class.

      For example:

      PS> $c = [WMICLASS]"root\cimv2:WIn32_Process"
      PS> $c |fl *
      Name             : Win32_Process
      __GENUS          : 1
      __CLASS          : Win32_Process
      __SUPERCLASS     : CIM_Process
      __DYNASTY        : CIM_ManagedSystemElement
      __RELPATH        : Win32_Process
      __PROPERTY_COUNT : 45
      __DERIVATION     : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemElement}
      __SERVER         : SERVER01
      __NAMESPACE      : ROOT\cimv2
      __PATH           : \\SERVER01\ROOT\cimv2:Win32_Process

      [WMI] is a type accelerator for ManagementObject. This has a string
      constructor that takes a local or absolute WMI path to a WMI instance
      and returns an object that is bound to that instance.

      For example:

      PS> $p = [WMI]'\\SERVER01\root\cimv2:Win32_Process.Handle="1204"'
      PS> $p.Name
      OUTLOOK.EXE

  WMI Troubleshooting

      The following problems are the most common problems that might occur
      when you try to connect to a remote computer.

    Problem 1: The remote computer is not online.

      If a computer is offline, you will not be able to connect to it by
      using WMI. You may receive the following error message:

          "Remote server machine does not exist or is unavailable"

      If you receive this error message, verify that the computer is online.
      Try to ping the remote computer.

    Problem 2: You do not have local administrator rights on the remote
               computer.

      To use WMI remotely, you must have local administrator rights on the
      remote computer. If you do not, access to that computer will be denied.

      To verify namespace security:

          a. Click Start, right-click My Computer, and then click Manage.

          b. In Computer Management, expand Services and Applications,
             right-click WMI Control, and then click Properties.

          c. In the WMI Control Properties dialog box, click  the Security tab.

    Problem 3: A firewall is blocking access to the remote computer.

      WMI uses the DCOM (Distributed COM) and RPC (Remote Procedure Call)
      protocols to traverse the network. By default, many firewalls block
      DCOM and RPC traffic. If your firewall is blocking these protocols,
      your connection will fail. For example, Windows Firewall in Microsoft
      Windows XP Service Pack 2 is configured to automatically block all
      unsolicited network traffic, including DCOM and WMI. In its default
      configuration, Windows Firewall rejects an incoming WMI request, and
      you receive the following error message:

          "Remote server machine does not exist or is unavailable"

  More Information about WMI

      For more information about WMI, see the following topics in the MSDN
      (Microsoft Developer Network) library:

          "About WMI:
          http://go.microsoft.com/fwlink/?LinkId=142212

          "WMI Troubleshooting"
          http://go.microsoft.com/fwlink/?LinkId=142213

      And, see "Secrets of Windows Management Instrumentation - Troubleshooting
      and Tips" in the Microsoft TechNet Script Center:

          http://go.microsoft.com/fwlink/?LinkId=142214

SEE ALSO
    Online version: http://go.microsoft.com/fwlink/?LinkId=142219
    Get-WmiObject
    Invoke-WmiMethod
    Register-WmiEvent
    Remove-WmiObject
    Set-WmiInstance


about_WS-Management_Cmdlets

TOPIC
    about_WS-Management_Cmdlets

SHORT DESCRIPTION
    Provides an overview of Web Services for Management (WS-Management) as
    background for using the WS-Management cmdlets in Windows PowerShell.

LONG DESCRIPTION
    This topic provides an overview of Web Services for Management
    (WS-Management) as background for using the WS-Management cmdlets in
    Windows PowerShell. This topic also provides links to more information
    about WS-Management. The Microsoft implementation of WS-Management is also
    known as Windows Remote Management (WinRM).

  About WS-Management

      Windows Remote Management is the Microsoft implementation
      of the WS-Management protocol, a standard SOAP-based, firewall-friendly
      protocol that allows hardware and operating systems from different
      vendors to interoperate. The WS-Management protocol specification
      provides a common way for systems to access and exchange management
      information across an information technology (IT) infrastructure.
      WS-Management and Intelligent Platform Management Interface (IPMI),
      along with the Event Collector, are components of the Windows Hardware
      Management features.

      The WS-Management protocol is based on the following standard Web service
      specifications: HTTPS, SOAP over HTTP (WS-I profile), SOAP 1.2,
      WS-Addressing, WS-Transfer, WS-Enumeration, and WS-Eventing.

  WS-Management and WMI

      WS-Management can be used to retrieve data exposed by Windows Management
      Instrumentation (WMI). You can obtain WMI data with scripts or
      applications that use the WS-Management Scripting API or through the
      WinRM command-line tool. WS-Management supports most of the familiar WMI
      classes and operations, including embedded objects. WS-Management can
      leverage WMI to collect data about resources or to manage resources on a
      Windows-based computers. That means that you can obtain data
      about objects such as disks, network adapters, services, or processes
      in your enterprise through the existing set of WMI classes. You can also
      access the hardware data that is available from the standard WMI IPMI
      provider.

  WS-Management Windows PowerShell Provider

      The WS-Management provider provides a hierarchical view into the
      available WS-Management configuration settings. The provider allows you
      to explore and set the various WS-Management configuration options.

  WS-Management Configuration

      If WS-Management is not installed and configured, Windows PowerShell
      remoting is not available, the WS-Management cmdlets do not run,
      WS-Management scripts do not run, and the WS-Management provider cannot
      perform data operations. The WS-Management command-line tool, WinRM,
      and event forwarding also depend on the WS-Management configuration.

  WS-Management Cmdlets

      WS-Management functionality is implemented in Windows PowerShell through
      a module that contains a set of cmdlets and the WS-Management provider.
      You can use these cmdlets to complete the end-to-end tasks necessary
      to manage WS-Management settings on local and remote computers.

      The following WS-Management cmdlets are available.

     Connection Cmdlets

     -- Connect-WSMan: Connects the local computer to the WS-Management
        (WinRM) service on a remote computer.

     -- Disconnect-WSMan: Disconnects the local computer from the WS-Management
        (WinRM) service on a remote computer.

     Management-Data Cmdlets

     -- Get-WSManInstance: Displays management information for a resource
        instance that is specified by a resource URI.

     -- Invoke-WSManAction: Invokes an action on the target object that
        is specified by the resource URI and by the selectors.

     -- New-WSManInstance: Creates a new management resource instance.

     -- Remove-WSManInstance: Deletes a management resource instance.

     -- Set-WSManInstance: Modifies the management information that is
        related to a resource.

     Setup and Configuration Cmdlets

     -- Set-WSManQuickConfig: Configures the local computer for remote
        management. You can use the Set-WSManQuickConfig cmdlet to configure
        WS-Management to allow remote connections to the WS-Management (WinRM)
        service. The Set-WSManQuickConfig cmdlet performs the following
        operations:

    - It determines whether the WS-Management (WinRM) service is running.
          If the WinRM service is not running, the Set-WSManQuickConfig cmdlet
          starts the service.

    - It sets the WS-Management (WinRM) service startup type to automatic.

    - It creates a listener that accepts requests from any IP address.
          The default transport protocol is HTTP.

    - It enables a firewall exception for WS-Management traffic.

    Note: To run this cmdlet in Windows Vista, Windows Server 2008, and
              later versions of Windows, you must start Windows PowerShell
              with the "Run as administrator" option.

     -- Test-WSMan: Verifies that WS-Management is installed and configured.
        The Test-WSMan cmdlet tests whether the WS-Management (WinRM)
        service is running and configured on a local or remote computer.

     -- Disable-WSManCredSSP: Disables CredSSP authentication on a client
        computer.

     -- Enable-WSManCredSSP: Enables CredSSP authentication on a client
        computer.

     -- Get-WSManCredSSP: Gets the CredSSP-related configuration for a
        client computer.

     WS-Management-Specific Cmdlets

     -- New-WSManSessionOption: Creates a WSManSessionOption object to use as
        input to one or more parameters of a WS-Management cmdlet.

  Additional WS-Management Information

    For more information about WS-Management, see the following topics in the
    MSDN (Microsoft Developer Network) library.

      "Windows Remote Management"
      http://go.microsoft.com/fwlink/?LinkId=142321

      "About Windows Remote Management"
      http://go.microsoft.com/fwlink/?LinkId=142322

      "Installation and Configuration for Windows Remote Management"
      http://go.microsoft.com/fwlink/?LinkId=142323

      "Windows Remote Management Architecture"
      http://go.microsoft.com/fwlink/?LinkId=142324

      "WS-Management Protocol"
      http://go.microsoft.com/fwlink/?LinkId=142325

      "Windows Remote Management and WMI"
      http://go.microsoft.com/fwlink/?LinkId=142326

      "Resource URIs"
      http://go.microsoft.com/fwlink/?LinkId=142327

      "Remote Hardware Management"
      http://go.microsoft.com/fwlink/?LinkId=142328

      "Events"
      http://go.microsoft.com/fwlink/?LinkId=142329

SEE ALSO
    Online version: http://go.microsoft.com/fwlink/?LinkId=142331
    Connect-WSMan
    Disable-WSManCredSSP
    Disconnect-WSMan
    Enable-WSManCredSSP
    Get-WSManCredSSP
    Get-WSManInstance
    Invoke-WSManAction
    New-WSManInstance
    Remove-WSManInstance
    Set-WSManInstance
    Set-WSManQuickConfig
    Set-WSManSessionOption
    Test-WSMan

KEYWORDS
    about_WSMAN about_WinRM


Windows PowerShell Cmdlet Help Topics

This section contains the help topics for the cmdlets that are installed with Windows PowerShell.

Display in verb order

Display in noun order

Cmdlets (In Verb Order)

Name | Description
Add-Computer | Adds computers to a domain or workgroup.
Add-Content | Adds content to the specified items, such as adding words to a file.
Add-History | Appends entries to the session history.
Add-Member | Adds a user-defined custom member to an instance of a Windows PowerShell object.
Add-PSSnapin | Adds one or more Windows PowerShell snap-ins to the current session.
Add-Type | Adds a .NET type (a class) to a Windows PowerShell session.
Checkpoint-Computer | Creates a system restore point on the local computer.
Clear-Content | Deletes the contents of a item, such as deleting the text from a file, but does not delete the item.
Clear-EventLog | Deletes all entries from specified event logs on the local or remote computers.
Clear-History | Deletes entries from the command history.
Clear-Item | Deletes the value of an item, but does not delete the item.
Clear-ItemProperty | Deletes the value of a property but it does not delete the property.
Clear-Variable | Deletes the value of a variable.
Compare-Object | Compares two sets of objects.
Complete-Transaction | Commits the active transaction.
Connect-WSMan | Connects to the WinRM service on a remote computer.
ConvertFrom-CSV | Converts object properties in CSV format into CSV versions of the original objects.
ConvertFrom-SecureString | Converts a secure string into an encrypted standard string.
ConvertFrom-StringData | Converts a string containing one or more "name=value" pairs to a hash table.
Convert-Path | Converts a path from a Windows PowerShell path to a Windows PowerShell provider path.
ConvertTo-CSV | Converts .NET objects into a series of comma-separated, variable-length (CSV) strings.
ConvertTo-Html | Converts .NET objects into HTML that can be displayed in a Web browser.
ConvertTo-SecureString | Converts encrypted standard strings to secure strings. It can also convert plain text to secure strings. It is used with ConvertFrom-SecureString and Read-Host.
ConvertTo-XML | Creates an XML-based representation of an object.
Copy-Item | Copies an item from one location to another within a namespace.
Copy-ItemProperty | Copies a property and value from a specified location to another location.
Debug-Process | Debugs one or more processes running on the local computer.
Disable-ComputerRestore | Disables the System Restore feature on the specified file system drive.
Disable-PSBreakpoint | Disables the breakpoints in the current console.
Disable-PSRemoting | Prevents the computer from receiving remote Windows PowerShell commands.
Disable-PSSessionConfiguration | Denies access to the session configurations on the local computer.
Disable-WSManCredSSP | Disables Credential Security Service Provider (CredSSP) authentication on a client computer.
Disconnect-WSMan | Disconnects the client from the WinRM service on a remote computer.
Enable-ComputerRestore | Enables the System Restore feature on the specified file system drive.
Enable-PSBreakpoint | Enables the breakpoints in the current console.
Enable-PSRemoting | Configures the computer to receive remote commands.
Enable-PSSessionConfiguration | Configures the computer to receive remote commands.
Enable-WSManCredSSP | Enables Credential Security Service Provider (CredSSP) authentication on a client computer.
Enter-PSSession | Starts an interactive session with a remote computer.
Exit-PSSession | Ends an interactive session with a remote computer.
Export-Alias | Exports information about currently-defined aliases to a file.
Export-Clixml | Creates an XML-based representation of an object or objects and stores it in a file.
Export-Console | Exports the names of snap-ins in the current session to a console file.
Export-Counter | The Export-Counter cmdlet exports performance counter data to log files.
Export-CSV | Converts .NET objects into a series of comma-separated, variable-length (CSV) strings and saves the strings in a CSV file.
Export-FormatData | Saves formatting data from the current session in a formatting file.
Export-ModuleMember | Specifies the module members that are exported.
Export-PSSession | Saves commands from another session in a module file.
ForEach-Object | Performs an operation against each of a set of input objects.
Format-Custom | Uses a customized view to format the output.
Format-List | Formats the output as a list of properties in which each property appears on a new line.
Format-Table | Formats the output as a table.
Format-Wide | Formats objects as a wide table that displays only one property of each object.
Get-Acl | Gets the security descriptor for a resource, such as a file or registry key.
Get-Alias | Gets the aliases for the current session.
Get-AuthenticodeSignature | Gets information about the Authenticode signature in a file.
Get-ChildItem | Gets the items and child items in one or more specified locations. (Like "dir".)
Get-Command | Gets basic information about cmdlets and about other elements of Windows PowerShell commands.
Get-ComputerRestorePoint | Gets the restore points on the local computer.
Get-Content | Gets the content of the item at the specified location.
Get-Counter | Gets performance counter data from local and remote computers.
Get-Credential | Gets a credential object based on a user name and password.
Get-Culture | Gets the culture currently set in the operating system.
Get-Date | Gets the current date and time.
Get-Event | Gets the events in the event queue.
Get-EventLog | Gets the events in a specified event log or a list of the event logs on a computer.
Get-EventSubscriber | Gets the event subscribers in the current session.
Get-ExecutionPolicy | Gets the execution policies in the current session.
Get-FormatData | Gets the formatting data in the current session.
Get-Help | Displays information about Windows PowerShell cmdlets and concepts.
Get-History | Gets a list of the commands entered during the current session.
Get-Host | Gets a reference to the current console host object. Displays Windows Powershell version and regional information by default.
Get-Hotfix | Gets the hotfixes that have been applied to the local and remote computers.
Get-Item | Gets the item at the specified location.
Get-ItemProperty | Gets the properties of a specified item.
Get-Location | Gets information about the current working location.
Get-Member | Gets the properties and methods of objects.
Get-Module | Gets the modules that have been imported, or can be imported, into the current session.
Get-PfxCertificate | Gets information about .pfx certificate files on the computer.
Get-Process | Gets the processes that are running on the local computer or a remote computer.
Get-PSBreakpoint | Gets the breakpoints set in the current console.
Get-PSCallStack | Displays the current call stack.
Get-PSDrive | Gets the Windows PowerShell drives in the current console.
Get-Job | Gets Windows PowerShell background jobs (PsJobs) that are running in the current console.
Get-PSProvider | Gets information about the specified Windows PowerShell provider.
Get-PSSession | Gets the Windows PowerShell sessions (PSSessions) in the current session.
Get-PSSessionConfiguration | Gets the session configurations registered on the computer.
Get-PSSnapin | Gets the Windows PowerShell snap-ins on the computer.
Get-Transaction | Gets the current (active) transaction.
Get-Random | Gets a random number or selects objects randomly from a collection.
Get-Service | Gets the services on a local or remote computer.
Get-TraceSource | Gets the Windows PowerShell components that are instrumented for tracing.
Get-UICulture | Gets the current user interface culture set in the operating system.
Get-Unique | Returns the unique items from a sorted list.
Get-Variable | Gets the variables in the current console.
Get-WinEvent | Gets events from event logs and event tracing log files on local and remote computers.
Get-WmiObject | Gets instances of WMI classes or information about available classes.
Get-WSManCredSSP | Gets the Credential Security Service Provider-related configuration for the client.
Get-WSManInstance | Displays management information for a resource instance specified by a Resource URI.
Group-Object | Groups objects that contain the same value for specified properties.
Import-Alias | Imports an alias list from a file.
Import-Clixml | Imports a CLIXML file and creates corresponding objects within Windows PowerShell.
Import-Counter | Imports performance counter log files (.blg, .csv, .tsv) and creates the objects that represent each counter sample in the log.
Import-CSV | Converts object properties in a CSV file into CSV versions of the original objects.
Import-LocalizedData | Imports language-specific data into scripts and functions based on the current culture setting of the operating system.
Import-Module | Adds modules to the current session.
Import-PSSession | Imports cmdlets, aliases, functions, and other command types from another session on a local or remote computer into the current session.
Invoke-Command | Runs commands on local and remote computers.
Invoke-Expression | Runs commands or expressions on the local computer.
Invoke-History | Runs commands from the session history.
Invoke-Item | Performs the default action on the specified item.
Invoke-WmiMethod | Calls WMI methods.
Invoke-WSManAction | Invokes an action on the object that is specified by the Resource URI and by the selectors.
Join-Path | Combines a path and child-path into a single path.
Limit-EventLog | Sets the event log properties that limit the size of the event log and the age of its entries.
Measure-Command | Measures the time it takes to run script blocks and cmdlets.
Measure-Object | Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as the text in files.
Move-Item | Moves an item from one location to another.
Move-ItemProperty | Moves a property from one location to another.
New-Alias | Creates a new alias.
New-Event | Creates a new event.
New-EventLog | Creates a new event log and a new event source on a local or remote computer.
New-Item | Creates a new item.
New-ItemProperty | Creates a new property for an item and sets its value. For example, you can use New-ItemProperty to create and change registry values and data, which are properties of a registry key.
New-Module | Creates a new dynamic module that exists only in memory.
New-ModuleManifest | Creates a new module manifest.
New-Object | Creates an instance of a .Net or COM object.
New-PSDrive | Creates a Windows PowerShell drive in the current console.
New-PSSession | Creates a persistent connection to a local or remote computer.
New-PSSessionOption | Creates an object that contains advanced options for a session.
New-Service | Creates a new Windows service.
New-TimeSpan | Creates an object that represents a time interval.
New-Variable | Creates a new variable.
New-WebServiceProxy | Creates a Web service proxy object that lets you use and manage the Web service in Windows PowerShell.
New-WSManInstance | Creates a new instance of a management resource.
New-WSManSessionOption | Creates a WSMan Session option hashtable to use as input parameters to the following WSMan cmdlets: Connect-WSMan, Get-WSManInstance, Invoke-WSManAction, Set-WSManInstance.
Out-Default | Sends the output to the default formatter and the default output cmdlet. It is a placeholder that lets you write your own Out-Default function or cmdlet.
Out-File | Sends output to a file.
Out-GridView | Sends output to an interactive table in a separate window.
Out-Host | Sends output to the console.
Out-Null | Deletes output instead of sending it to the console.
Out-Printer | Sends output to a printer.
Out-String | Sends objects to the host as a series of strings.
Pop-Location | Changes to the location most recently pushed onto the stack by Push-Location.
Push-Location | Adds the current location to the top of a list of locations ("stack").
Read-Host | Reads a line of input from the console.
Receive-Job | Gets the output and errors of the background jobs (PsJobs) run in the current console.
Register-EngineEvent | Subscribes to events that are generated by the Windows PowerShell engine and by the New-Event cmdlet.
Register-ObjectEvent | Subscribes to the events that are generated by a .NET object.
Register-PSSessionConfiguration | Creates and registers a new session configuration.
Register-WmiEvent | Subscribes to an event generated by a WMI object.
Remove-Computer | Removes computers from workgroups or domains.
Remove-Event | Deletes events from the event queue.
Remove-EventLog | Deletes an event log or unregisters an event source.
Remove-Item | Deletes the specified items.
Remove-ItemProperty | Deletes the property and its value from an item.
Remove-Job | Deletes a Windows PowerShell background job.
Remove-Module | Removes modules from the current session.
Remove-PSBreakpoint | Deletes breakpoints from the current console.
Remove-PSDrive | Removes a Windows PowerShell drive from its location.
Remove-PSSession | Closes one or more Windows PowerShell sessions (PSSessions).
Remove-PSSnapin | Removes Windows PowerShell snap-ins from the current session.
Remove-Variable | Deletes a variable and its value.
Remove-WmiObject | Deletes WMI classes and instances.
Remove-WSManInstance | Deletes a management resource instance.
Rename-Item | Renames an item in a Windows PowerShell provider namespace.
Rename-ItemProperty | Renames a property of an item.
Reset-ComputerMachinePassword | Resets the machine account password for the computer.
Resolve-Path | Resolves the wildcard characters in a path and displays the path contents.
Restart-Computer | Restarts ("reboots") the operating system on local and remote computers.
Restart-Service | Stops and then starts one or more services.
Restore-Computer | Starts a system restore on the local computer.
Resume-Service | Resumes one or more suspended (paused) services.
Select-Object | Selects specified properties of an object or set of objects. It can also select unique objects from an array of objects or it can select a specified number of objects from the beginning or end of an array of objects.
Select-String | Finds text in strings and files.
Select-Xml | Finds text in an XML document.
Send-MailMessage | Sends an e-mail message.
Set-Acl | Changes the security descriptor of a specified resource, such as a file or a registry key.
Set-Alias | Creates or changes an alias (alternate name) for a cmdlet or command element.
Set-AuthenticodeSignature | Adds an Authenticode signature to a Windows PowerShell script or other file.
Set-Content | Writes or replaces the content in an item with new content.
Set-Date | Changes the system time on the computer to a time that you specify.
Set-ExecutionPolicy | Changes the user preference for the execution policy of the shell.
Set-Item | Changes the value of an item to the value specified in the command.
Set-ItemProperty | Creates or changes the value of a property of an item.
Set-Location | Sets the current working location to a specified location.
Set-PSBreakpoint | Sets a breakpoint on a line, command, or variable.
Set-PSDebug | Turns script debugging features on and off, sets the trace level and toggles strict mode.
Set-PSSessionConfiguration | Changes the properties of a registered session configuration.
Set-Service | Starts, stops, and suspends a service, and changes its properties.
Set-StrictMode | Establishes and enforces coding rules in expressions, scripts, and script blocks.
Set-TraceSource | Configures, starts, and stops a trace of Windows PowerShell components.
Set-Variable | Sets the value of a variable. Creates the variable if one with the requested name does not exist.
Set-WmiInstance | Creates or modifies instances of WMI classes.
Set-WSManInstance | Modifies management information related to a resource.
Set-WSManQuickConfig | Configures the local machine for remote management.
Show-Eventlog | Displays the event logs of the local or a remote computer in Event Viewer.
Sort-Object | Sorts objects by property values.
Split-Path | Returns the specified part of a path.
Start-Process | Starts one or more processes on the local computer.
Start-Job | Starts a Windows PowerShell background job (PsJob).
Start-Transaction | Starts a transaction.
Start-Service | Starts one or more stopped services.
Start-Sleep | Suspend shell, script, or runspace activity for the specified period of time.
Start-Transcript | Creates a record of all or part of a Windows PowerShell session in a text file.
Stop-Computer | Shuts down local and remote computers.
Stop-Process | Stops one or more running processes.
Stop-Job | Stops a Windows PowerShell background job (PsJob).
Stop-Service | Stops one or more running services.
Stop-Transcript | Stops a transcript.
Suspend-Service | Suspends (pauses) one or more running services.
Tee-Object | Saves command output in a file or variable and displays it in the console.
Test-ComputerSecureChannel | Tests and repairs the secure channel between the local computer and its domain.
Test-Connection | Sends ICMP echo request packets ("pings") to one or more computers.
Test-ModuleManifest | Verifies that a module manifest accurately describes the contents of a module.
Test-Path | Determines whether all elements of a path exist.
Test-WSMan | Tests whether the WinRM service is running on a local or remote computer.
Trace-Command | Configures and starts a trace of the specified expression or command.
Undo-Transaction | Rolls back the active transaction.
Unregister-Event | Cancels an event subscription.
Unregister-PSSessionConfiguration | Deletes a registered session configurations from the computer.
Update-FormatData | Updates and appends format data files.
Update-List | Adds and removes items from a property value that contains a collection of objects.
Update-TypeData | Updates the current extended type configuration by reloading the *.types.ps1xml files.
Use-Transaction | Adds the script block to the active transaction.
Wait-Event | Waits until a particular event is raised before continuing to run.
Wait-Process | Waits for the processes to be stopped before accepting more input.
Wait-Job | Suppresses the command prompt until one or all of the Windows PowerShell background jobs (PsJobs) are complete.
Where-Object | Creates a filter that controls which objects will be passed along a command pipeline.
Write-Debug | Writes a debugging message to the console.
Write-Error | Writes an object to the error pipeline.
Write-EventLog | Writes an event to an event log.
Write-Host | Writes customized output to a host.
Write-Output | Sends the objects to the next command in the pipeline. If the command is the last in the pipeline, the objects are displayed on the console.
Write-Progress | Displays a progress bar within a Windows PowerShell command window.
Write-Verbose | Writes text to the verbose message stream in Windows PowerShell.
Write-Warning | Writes a warning message.

Cmdlets (In Noun Order)

Display in verb order

Name | Description
Get-Acl | Gets the security descriptor for a resource, such as a file or registry key.
Set-Acl | Changes the security descriptor of a specified resource, such as a file or a registry key.
Export-Alias | Exports information about currently-defined aliases to a file.
Get-Alias | Gets the aliases for the current session.
Import-Alias | Imports an alias list from a file.
New-Alias | Creates a new alias.
Set-Alias | Creates or changes an alias (alternate name) for a cmdlet or command element.
Get-AuthenticodeSignature | Gets information about the Authenticode signature in a file.
Set-AuthenticodeSignature | Adds an Authenticode signature to a Windows PowerShell script or other file.
Get-ChildItem | Gets the items and child items in one or more specified locations. (Like "dir".)
Export-Clixml | Creates an XML-based representation of an object or objects and stores it in a file.
Import-Clixml | Imports a CLIXML file and creates corresponding objects within Windows PowerShell.
Get-Command | Gets basic information about cmdlets and about other elements of Windows PowerShell commands.
Invoke-Command | Runs commands on local and remote computers.
Measure-Command | Measures the time it takes to run script blocks and cmdlets.
Trace-Command | Configures and starts a trace of the specified expression or command.
Add-Computer | Adds computers to a domain or workgroup.
Checkpoint-Computer | Creates a system restore point on the local computer.
Remove-Computer | Removes computers from workgroups or domains.
Restart-Computer | Restarts ("reboots") the operating system on local and remote computers.
Restore-Computer | Starts a system restore on the local computer.
Stop-Computer | Shuts down local and remote computers.
Reset-ComputerMachinePassword | Resets the machine account password for the computer.
Disable-ComputerRestore | Disables the System Restore feature on the specified file system drive.
Enable-ComputerRestore | Enables the System Restore feature on the specified file system drive.
Get-ComputerRestorePoint | Gets the restore points on the local computer.
Test-ComputerSecureChannel | Tests and repairs the secure channel between the local computer and its domain.
Test-Connection | Sends ICMP echo request packets ("pings") to one or more computers.
Export-Console | Exports the configuration of the current console to a file so that you can reuse or share it.
Add-Content | Adds content to the specified items, such as adding words to a file.
Clear-Content | Deletes the contents of a item, such as deleting the text from a file, but does not delete the item.
Get-Content | Gets the content of the item at the specified location.
Set-Content | Writes or replaces the content in an item with new content.
Export-Counter | The Export-Counter cmdlet exports performance counter data to log files.
Get-Counter | Gets performance counter data from local and remote computers.
Import-Counter | Imports performance counter log files (.blg, .csv, .tsv) and creates the objects that represent each counter sample in the log.
Get-Credential | Gets a credential object based on a user name and password.
ConvertFrom-CSV | Converts object properties in CSV format into CSV versions of the original objects.
ConvertTo-CSV | Converts .NET objects into a series of comma-separated, variable-length (CSV) strings.
Export-CSV | Converts .NET objects into a series of comma-separated, variable-length (CSV) strings and saves the strings in a CSV file.
Import-CSV | Converts object properties in a CSV file into CSV versions of the original objects.
Get-Culture | Gets the culture currently set in the operating system.
Format-Custom | Uses a customized view to format the output.
Get-Date | Gets the current date and time.
Set-Date | Changes the system time on the computer to a time that you specify.
Write-Debug | Writes a debugging message to the console.
Out-Default | Sends the output to the default formatter and the default output cmdlet. It is a placeholder that lets you write your own Out-Default function or cmdlet.
Register-EngineEvent | Subscribes to events that are generated by the Windows PowerShell engine and by the New-Event cmdlet.
Write-Error | Writes an object to the error pipeline.
Get-Event | Gets the events in the event queue.
New-Event | Creates a new event.
Remove-Event | Deletes events from the event queue.
Unregister-Event | Cancels an event subscription.
Wait-Event | Waits until a particular event is raised before continuing to run.
Clear-EventLog | Deletes all entries from specified event logs on the local or remote computers.
Get-EventLog | Gets the events in a specified event log or a list of the event logs on a computer.
Limit-EventLog | Sets the event log properties that limit the size of the event log and the age of its entries.
New-EventLog | Creates a new event log and a new event source on a local or remote computer.
Remove-EventLog | Deletes an event log or unregisters an event source.
Show-Eventlog | Displays the event logs of the local or a remote computer in Event Viewer.
Write-EventLog | Writes an event to an event log.
Get-EventSubscriber | Gets the event subscribers in the current session.
Get-ExecutionPolicy | Gets the current execution policies in the current session.
Set-ExecutionPolicy | Changes the user preference for the execution policy of the shell.
Invoke-Expression | Runs commands on a local or remote computer.
Out-File | Sends output to a file.
Export-FormatData | Saves formatting data from the current session in a formatting file.
Get-FormatData | Gets the formatting data in the current session.
Update-FormatData | Updates and appends format data files.
Out-GridView | Sends output to an interactive table in a separate window.
Get-Help | Displays information about Windows PowerShell cmdlets and concepts.
Add-History | Appends entries to the session history.
Clear-History | Deletes entries from the command history.
Get-History | Gets a list of the commands entered during the current session.
Invoke-History | Runs commands from the session history.
Get-Host | Gets a reference to the current console host object. Displays Windows Powershell version and regional information by default.
Out-Host | Sends output to the console.
Read-Host | Reads a line of input from the console.
Write-Host | Writes customized output to a host.
Get-Hotfix | Gets the hotfixes that have been applied to the local and remote computers.
ConvertTo-Html | Converts .NET objects into HTML that can be displayed in a Web browser.
Clear-Item | Deletes the value of an item, but does not delete the item.
Copy-Item | Copies an item from one location to another within a namespace.
Get-Item | Gets the item at the specified location.
Invoke-Item | Performs the default action on the specified item.
Move-Item | Moves an item from one location to another.
New-Item | Creates a new item.
Remove-Item | Deletes the specified items.
Rename-Item | Renames an item in a Windows PowerShell provider namespace.
Set-Item | Changes the value of an item to the value specified in the command.
Clear-ItemProperty | Creates or changes the value of a property of an item.
Copy-ItemProperty | Copies a property and value from a specified location to another location.
Get-ItemProperty | Gets the properties of a specified item.
Move-ItemProperty | Moves a property from one location to another.
New-ItemProperty | Creates a new property for an item and sets its value. For example, you can use New-ItemProperty to create and change registry values and data, which are properties of a registry key.
Remove-ItemProperty | Deletes the property and its value from an item.
Rename-ItemProperty | Renames a property of an item.
Set-ItemProperty | Creates or changes the value of a property of an item.
Format-List | Formats the output as a list of properties in which each property appears on a new line.
Update-List | Adds and removes items from a property value that contains a collection of objects.
Import-LocalizedData | Imports language-specific data into scripts and functions based on the current culture setting of the operating system.
Get-Location | Gets information about the current working location.
Pop-Location | Changes to the location most recently pushed onto the stack by Push-Location.
Push-Location | Adds the current location to the top of a list of locations ("stack").
Set-Location | Sets the current working location to a specified location.
Send-MailMessage | Sends an e-mail message.
Add-Member | Adds a user-defined custom member to an instance of a Windows PowerShell object.
Get-Member | Gets the properties and methods of objects.
Export-ModuleMember | Specifies the module members that are exported.
Get-Module | Gets the modules that have been imported, or can be imported, into the current session.
Import-Module | Creates a new dynamic module that exists only in memory.
New-Module | Creates a new dynamic module that exists only in memory.
New-ModuleManifest | Creates a new module manifest.
Remove-Module | Removes modules from the current session.
Test-ModuleManifest | Verifies that a module manifest accurately describes the contents of a module.
Out-Null | Deletes output instead of sending it to the console.
Compare-Object | Compares two sets of objects.
ForEach-Object | Performs an operation against each of a set of input objects.
Group-Object | Groups objects that contain the same value for specified properties.
Measure-Object | Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as the text in files.
New-Object | Creates an instance of a .Net or COM object.
Select-Object | Selects specified properties of an object or set of objects. It can also select unique objects from an array of objects or it can select a specified number of objects from the beginning or end of an array of objects.
Sort-Object | Sorts objects by property values.
Tee-Object | Saves command output in a file or variable and displays it in the console.
Where-Object | Creates a filter that controls which objects will be passed along a command pipeline.
Register-ObjectEvent | Subscribes to the events that are generated by a .NET object.
Write-Output | Sends the objects to the next command in the pipeline. If the command is the last in the pipeline, the objects are displayed on the console.
Convert-Path | Converts a path from a Windows PowerShell path to a Windows PowerShell provider path.
Join-Path | Combines a path and child-path into a single path.
Resolve-Path | Resolves the wildcard characters in a path and displays the path contents.
Split-Path | Returns the specified part of a path.
Test-Path | Determines whether all elements of a path exist.
Get-PfxCertificate | Gets information about .pfx certificate files on the computer.
Out-Printer | Sends output to a printer.
Debug-Process | Debugs one or more processes running on the local computer.
Get-Process | Gets the processes that are running on the local computer or a remote computer.
Start-Process | Starts one or more processes on the local computer.
Stop-Process | Stops one or more running processes.
Wait-Process | Waits for the processes to be stopped before accepting more input.
Write-Progress | Displays a progress bar within a Windows PowerShell command window.
Disable-PSBreakpoint | Disables the breakpoints in the current console.
Enable-PSBreakpoint | Enables the breakpoints in the current console.
Get-PSBreakpoint | Gets the breakpoints set in the current console.
Remove-PSBreakpoint | Deletes breakpoints from the current console.
Set-PSBreakpoint | Sets a breakpoint on a line, command, or variable.
Get-PSCallStack | Displays the current call stack.
Set-PSDebug | Turns script debugging features on and off, sets the trace level and toggles strict mode.
Get-PSDrive | Gets the Windows PowerShell drives in the current console.
New-PSDrive | Creates a Windows PowerShell drive in the current console.
Remove-PSDrive | Removes a Windows PowerShell drive from its location.
Get-Job | Gets Windows PowerShell background jobs (PsJobs) that are running in the current console.
Receive-Job | Gets the output and errors of the background jobs (PsJobs) run in the current console.
Remove-Job | Deletes a Windows PowerShell background job (PsJob) .
Start-Job | Starts a Windows PowerShell background job (PsJob).
Stop-Job | Stops a Windows PowerShell background job (PsJob).
Wait-Job | Suppresses the command prompt until one or all of the Windows PowerShell background jobs (PsJobs) are complete.
Get-PSProvider | Gets information about the specified Windows PowerShell provider.
Disable-PSRemoting | Prevents the computer from receiving remote Windows PowerShell commands.
Enable-PSRemoting | Configures the computer to receive remote commands.
Enter-PSSession | Starts an interactive session with a remote computer.
Exit-PSSession | Ends an interactive session with a remote computer.
Export-PSSession | Saves commands from another session in a module file.
Get-PSSession | Gets the Windows PowerShell sessions (PSSessions) in the current session.
Import-PSSession | Imports cmdlets, aliases, functions, and other command types from another session on a local or remote computer into the current session.
New-PSSession | Creates a persistent connection to a local or remote computer.
Remove-PSSession | Closes one or more Windows PowerShell sessions (PSSessions).
Disable-PSSessionConfiguration | Denies access to the session configurations on the local computer.
Enable-PSSessionConfiguration | Configures the computer to receive remote commands.
Get-PSSessionConfiguration | Gets the session configurations registered on the computer.
Register-PSSessionConfiguration | Creates and registers a new session configuration.
Set-PSSessionConfiguration | Changes the properties of a registered session configuration.
Unregister-PSSessionConfiguration | Deletes a registered session configurations from the computer.
New-PSSessionOption | Creates an object that contains advanced options for a session.
Add-PSSnapin | Adds one or more Windows PowerShell snap-ins to the current session.
Get-PSSnapin | Gets the Windows PowerShell snap-ins on the computer.
Remove-PSSnapin | Removes Windows PowerShell snap-ins from the current session.
Complete-Transaction | Commits the active transaction.
Get-Transaction | Gets the current (active) transaction.
Start-Transaction | Starts a transaction.
Undo-Transaction | Rolls back the active transaction.
Use-Transaction | Adds the script block to the active transaction.
Get-Random | Gets a random number or selects objects randomly from a collection.
ConvertFrom-SecureString | Converts a secure string into an encrypted standard string.
ConvertTo-SecureString | Converts encrypted standard strings to secure strings. It can also convert plain text to secure strings. It is used with ConvertFrom-SecureString and Read-Host.
Get-Service | Gets the services on a local or remote computer.
New-Service | Creates a new entry for a Windows Service in the registry and the Service Database.
Restart-Service | Stops and then starts one or more services.
Resume-Service | Resumes one or more suspended (paused) services.
Set-Service | Starts, stops, and suspends a service, and changes its properties.
Start-Service | Starts one or more stopped services.
Stop-Service | Stops one or more running services.
Suspend-Service | Suspends (pauses) one or more running services.
Start-Sleep | Suspend shell, script, or runspace activity for the specified period of time.
Set-StrictMode | Establishes and enforces coding rules in expressions, scripts, and script blocks.
Out-String | Sends objects to the host as a series of strings.
Select-String | Finds text in strings and files.
ConvertFrom-StringData | Converts a string containing one or more "name=value" pairs to a hash table.
Format-Table | Formats the output as a table.
New-TimeSpan | Creates an object that represents a time interval.
Get-TraceSource | Gets the Windows PowerShell components that are instrumented for tracing.
Set-TraceSource | Configures, starts, and stops a trace of Windows PowerShell components.
Start-Transcript | Creates a record of all or part of a Windows PowerShell session in a text file.
Stop-Transcript | Stops a transcript.
Add-Type | Adds a .NET type (a class) to a Windows PowerShell session.
Update-TypeData | Updates the current extended type configuration by reloading the *.types.ps1xml files.
Get-UICulture | Gets the current user interface culture set in the operating system.
Get-Unique | Returns the unique items from a sorted list.
Clear-Variable | Deletes the value of a variable.
Get-Variable | Gets the variables in the current console.
New-Variable | Creates a new variable.
Remove-Variable | Deletes a variable and its value.
Set-Variable | Sets the value of a variable. Creates the variable if one with the requested name does not exist.
Write-Verbose | Writes text to the verbose message stream in Windows PowerShell.
Write-Warning | Writes a warning message.
New-WebServiceProxy | Creates a Web service proxy object that lets you use and manage the Web service in Windows PowerShell.
Format-Wide | Formats objects as a wide table that displays only one property of each object.
Get-WinEvent | Gets events from event logs and event tracing log files on local and remote computers.
Register-WmiEvent | Subscribes to an event generated by a WMI object.
Set-WmiInstance | Creates or modifies instances of WMI classes.
Invoke-WmiMethod | Calls WMI methods.
Get-WmiObject | Gets instances of WMI classes or information about available classes.
Remove-WmiObject | Deletes WMI classes and instances.
Connect-WSMan | Connects to the WinRM service on a remote computer.
Disable-WSManCredSSP | Disables Credential Security Service Provider (CredSSP) authentication on a client computer.
Disconnect-WSMan | Disconnects the client from the WinRM service on a remote computer.
Enable-WSManCredSSP | Enables Credential Security Service Provider (CredSSP) authentication on a client computer.
Get-WSManCredSSP | Gets the Credential Security Service Provider-related configuration for the client.
Get-WSManInstance | Displays management information for a resource instance specified by a Resource URI.
Invoke-WSManAction | Invokes an action on the object that is specified by the Resource URI and by the selectors.
New-WSManInstance | Creates a new instance of a management resource.
New-WSManSessionOption | Creates a WSMan Session option hashtable to use as input parameters to the following WSMan cmdlets: Connect-WSMan, Get-WSManInstance, Invoke-WSManAction, Set-WSManInstance.
Remove-WSManInstance | Deletes a management resource instance.
Set-WSManInstance | Modifies management information related to a resource.
Set-WSManQuickConfig | Configures the local machine for remote management.
Test-WSMan | Tests whether the WinRM service is running on a local or remote computer.
ConvertTo-XML | Creates an XML-based representation of an object.
Select-Xml | Finds text in an XML document.

See Also

  • Windows PowerShell About Help Topics
  • Windows PowerShell Provider Help Topics
  • PowerShell.exe Console Help
  • Windows PowerShell SDK


Add-Computer

Add the local computer to a domain or workgroup.

Syntax

Add-Computer [-DomainName] <string> [-Credential <PSCredential>] [-OUPath <string>] [-Server <string>] [-Unsecure] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Add-Computer [-WorkGroupName] <string> [-Credential <PSCredential>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Add-Computer cmdlet adds the local computer to a domain or workgroup, or moves it from one domain to another. It also creates a domain account if the computer is added to the domain without an account.

You can use the parameters of this cmdlet to specify an organizational unit (OU) and domain controller or to perform an unsecure join.

To get the results of the command, use the Verbose and PassThru parameters.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | Current User Account Credentials
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DomainName <string>

Specifies a domain for the computer account. This parameter is required.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OUPath <string>

Specifies an organizational unit (OU) for the domain account. Enter the full distinguished name of the OU. The default value is the default OU for machine objects in the domain.

Required? | false
Position? | named
Default Value | The default OU for machine objects for in the domain
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns the results of the command. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Server <string>

Specifies the name of a domain controller that adds the computer to the domain. Enter the name in DomainName\ComputerName format. The default is the local computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Unsecure

Performs an unsecure join.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WorkGroupName <string>

Specifies the name of a work group for the computer. If you omit this parameter, the computer is joined to a domain.

Required? | true
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Add-Computer.
Outputs | Microsoft.PowerShell.Commands.ComputerChangeInfo When you use the PassThru parameter, Add-Computer returns a ComputerChangeInfo object. Otherwise, this cmdlet does not generate any output.

Example 1

C:\PS>add-computer -domainname Domain01; restart-computer

These commands add the local computer to the Domain01 domain using the credentials of the current user.

The first command adds the computer to the domain. The second command uses the Restart-Computer cmdlet to restart the computer, which completes the join operation. The semi-colon (;) separates the two commands.

Example 2

C:\PS>add-computer -workgroupname WORKGROUP-A

This command adds the local computer to the Workgroup-A workgroup.

Example 3

C:\PS>add-computer -DomainName Domain01 -Server Domain01\DC01 -passthru -verbose

This command adds the local computer to the Domain01 domain by using the Domain01\DC01 domain controller.

The command uses the PassThru and Verbose parameters to get detailed information about the results of the command.

Example 4

C:\PS>Add-Computer -domainname Domain02 -OUPath OU=testOU,DC=domain,DC=Domain,DC=com

This command adds the Server01 and Server02 computers to the Domain02 domain. It uses the OUPath command to specify the organization unit for the new accounts.

Example 5

C:\PS>Add-Computer -domainname Domain02 -cred Domain02\Admin02 -passthru

This command adds the local computer to the Domain02 domain by using the credentials of a domain administrator. The command uses the PassThru parameter to generate a brief report about the results of the command.

See Also

  • Checkpoint-Computer
  • Remove-Computer
  • Restart-Computer
  • Restore-Computer
  • Stop-Computer
  • Test-Connection


Add-Content

Adds content to the specified items, such as adding words to a file.

Syntax

Add-Content [-LiteralPath] <string[]> [-Value] <Object[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Add-Content [-Path] <string[]> [-Value] <Object[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Add-Content cmdlet appends content to a specified item or file. You can specify the content by typing the content in the command or by specifying an object that contains the content.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Overrides the read-only attribute, allowing you to add content to a read-only file.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Adds only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the path to the items that receive the additional content. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the added content. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the items that receive the additional content. Wildcards are permitted. If you specify multiple paths, use commas to separate the paths.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Value <Object[]>

Specifies the content to be added. Type a quoted string, such as "This data is for internal use only", or specify an object that contains content, such as the DateTime object that Get-Date generates.

You cannot specify the contents of a file by typing its path, because the path is just a string, but you can use a Get-Content command to get the content and pass it to the Value parameter.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Object You can pipe the objects to be added (the Value) to Add-Content.
Outputs | None or System.String When you use the Passthru parameter, Add-Content generates a System.String object representing the content. Otherwise, this cmdlet does not generate any output.

Notes

When you pipe an object to Add-Content, the object is converted to a string before it is added to the item. The object type determines the string format, but the format might be different than the default display of the object. To control the string format, use the formatting parameters of the sending cmdlet.

You can also refer to Add-Content by its built-in alias, "ac". For more information, see about_Aliases.

The Add-Content cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>add-content -path *.txt -exclude help* -value "END"

This command adds "END" to all text files in the current directory, except for those with file names that begin with "help".

Example 2

C:\PS>add-content -Path file1.log, file2.log -Value (get-date) -passthru

This command adds the date to the end of the File1.log and File2.log files and then displays the date at the command line. The command uses the Get-Date cmdlet to get the date, and it uses the Value parameter to pass the date to Add-Content. The PassThru parameter passes an object representing the added content through the pipeline. Because there is no other cmdlet to receive the passed object, it is displayed at the command line.

Example 3

C:\PS>add-content -path monthly.txt -value (get-content c:\rec1\weekly.txt)

This command adds the contents of the Weekly.txt file to the end of the Monthly.txt file. It uses the Get-Content cmdlet to get the contents of the Weekly.txt file, and it uses the Value parameter to pass the content of weekly.txt to Add-Content. The parentheses ensure that the Get-Content command is complete before the Add-Content command begins.

You can also copy the content of Weekly.txt to a variable, such as $w, and then use the Value parameter to pass the variable to Add-Content. In that case, the command would be "add-content -path monthly.txt -value $w".

Example 4

C:\PS>add-content -value (get-content test.log) -path C:\tests\test134\logs\test134.log

This command creates a new directory and file and copies the content of an existing file to the newly created file.

This command uses the Add-Content cmdlet to add the content. The value of the Value parameter is a Get-Content command that gets content from an existing file, Test.log.

The value of the path parameter is a path that does not exist when the command runs. In this example, only the C:\Tests directories exist. The command creates the remaining directories and the Test134.log file.

The Force parameter is not required for this command. Add-Content creates directories to complete a path even without the Force parameter.

See Also

  • about_Providers
  • Get-Content
  • Set-Content
  • Clear-Content
  • Get-Item


Add-History

Appends entries to the session history.

Syntax

Add-History [[-InputObject] <PSObject[]>] [-PassThru] [<CommonParameters>]

Description

The Add-History cmdlet adds entries to the end of the session history, that is, the list of commands entered during the current session.

You can use the Get-History cmdlet to get the commands and pass them to Add-History, or you can export the commands to a CSV or XML file, then import the commands, and pass the imported file to Add-History. You can use this cmdlet to add specific commands to the history or to create a single history file that includes commands from more than one session.

Parameters

-InputObject <PSObject[]>

Adds the specified HistoryInfo object to the session history. You can use this parameter to submit a HistoryInfo object from Get-History, Import-Clixml, or Import-CSV to Add-History.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-PassThru

Returns a history object for each history entry. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | Microsoft.PowerShell.Commands.HistoryInfo You can pipe a HistoryInfo object to Add-History.
Outputs | None or Microsoft.PowerShell.Commands.HistoryInfo When you use the PassThru parameter, Add-History generates a HistoryInfo object. Otherwise, this cmdlet does not generate any output.

Notes

The session history is a list of the commands entered during the session along with the ID. The session history represents the order of execution, the status, and the start and end times of the command. As you enter each command, Windows PowerShell adds it to the history so that you can reuse it. For more information about the session history, see about_History.

To specify the commands to add to the history, use the InputObject parameter. The Add-History command accepts only HistoryInfo objects, such as those generated for each command by Get-History. You cannot pass it a path and file name or a list of commands.

You can use the -InputObject parameter to pass a file of HistoryInfo objects to Add-History. To do so, export the results of a Get-History command to a file by using Export-CSV or Export-Clixml and then import the file by using Import-CSV or Import-Clixml. You can then pass the file of imported HistoryInfo objects to Add-History through a pipeline or in a variable. For more information, see the examples.

The file of HistoryInfo objects that you pass to Add-History must include the type information, column headings, and all of the properties of the HistoryInfo objects. If you intend to pass the objects back to Add-History, do not use the NoTypeInformation parameter of Export-CSV and do not delete the type information, column headings, or any fields in the file.

To edit the session history, export the session to a CSV or XML file, edit the file, import the file, and use Add-History to append it to the current session history.

Example 1

C:\PS>get-history | export-csv c:\testing\history.csv

C:\PS>import-csv history.csv | add-history

These commands add the commands typed in one Windows PowerShell session to the history of a different Windows PowerShell session. The first command gets objects representing the commands in the history and exports them to the History.csv file. The second command is typed at the command line of a different session. It uses the Import-Csv cmdlet to import the objects in the History.csv file. The pipeline operator passes the objects to the Add-History cmdlet, which adds the objects representing the commands in the History.csv file to the current session history.

Example 2

C:\PS>import-clixml c:\temp\history.xml | add-history -passthru | foreach-object {invoke-history}

This command imports commands from the History.xml file, adds them to the current session history, and then executes the commands in the combined history.

The first command uses the Import-Clixml command to import a command history that was exported to the History.xml file. The pipeline operator (|) passes the commands to the Add-History parameter, which adds the commands to the current session history. The PassThru parameter passes the objects representing the added commands down the pipeline.

The command then uses the ForEach-Object cmdlet to apply the Invoke-History command to each of the commands in the combined history. The Invoke-History command is formatted as a script block, which is enclosed in braces ({}) because ForEach-Object requires a script block even when there is only one command to apply.

Example 3

C:\PS>get-history -id 5 -count 5 | add-history

This command adds the first five commands in the history to the end of the history list. It uses the Get-History cmdlet to get the five commands ending in command 5. The pipeline operator (|) passes them to the Add-History cmdlet, which appends them to the current history. The Add-History command does not include any parameters, but Windows PowerShell associates the objects passed through the pipeline with the InputObject parameter.

Example 4

C:\PS>$a = import-csv c:\testing\history.csv

C:\PS>add-history -inputobject $a -passthru

These commands add the commands in the History.csv file to the current session history. The first command uses the Import-Csv cmdlet to import the commands in the History.csv file and store its contents in the variable $a. The second command uses the Add-History cmdlet to add the commands from History.csv to the current session history. It uses the InputObject parameter to specify the $a variable and the PassThru parameter to generate an object to display at the command line. Without the PassThru parameter, Add-History does not generate any output to display.

Example 5

C:\PS>add-history -inputobject (import-clixml c:\temp\history01.xml)

This command adds the commands in the History01.xml file to the current session history. It uses the InputObject parameter to pass the results of the command in parentheses to Add-History. The command in parentheses, which is executed first, imports the History01.xml file into Windows PowerShell. Add-History then adds the commands in the file to the session history.

See Also

  • about_History
  • Get-History
  • Invoke-History
  • Clear-History


Add-Member

Adds a user-defined custom member to an instance of a Windows PowerShell object.

Syntax

Add-Member [-MemberType] {<AliasProperty> | <CodeProperty> | <Property> | <NoteProperty> | <ScriptProperty> | <Properties> | <PropertySet> | <Method> | <CodeMethod> | <ScriptMethod> | <Methods> | <ParameterizedProperty> | <MemberSet> | <Event> | <All>} [-Name] <string> -InputObject <psobject> [[-Value] <Object>] [[-SecondValue] <Object>] [-Force] [-PassThru] [<CommonParameters>]

Description

The Add-Member cmdlet adds a user-defined custom member to an instance of a Windows PowerShell object. It lets you add the following types of members: AliasProperty, CodeProperty, NoteProperty, ScriptProperty, PropertySet, CodeMethod, MemberSet, and ScriptMethod. You set the initial value of the member by using the Value parameter. In the case of AliasProperty, ScriptProperty, CodeProperty, and CodeMethod, you can supply additional information by using the SecondValue parameter.

The additional members are added to the particular instance of the object that you pipe to Add-Member or specify using the InputObject parameter. The additional member is available only while that instance exists. You can use the Export-Clixml cmdlet to save the instance, including the additional members, to a file. The information stored in that file can be used by the Import-Clixml cmdlet to re-create the instance of the object.

Parameters

-Force

Adds a new member even if one with the same name already exists. Does not work for core members of a type.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the object to which the new member is added. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-MemberType <PSMemberTypes>

Specifies the type of the member to add. This parameter is mandatory.

The valid values for this parameter are:

-- AliasProperty: A property that defines a new name for an existing property.

-- CodeMethod: A method that references a static method of a Microsoft .NET Framework class.

-- CodeProperty: A property that references a static property of a .NET Framework class.

-- MemberSet: A predefined collection of properties and methods, such as PSBase, PSObject, and PSTypeNames.

-- Method: A method of the underlying .NET Framework object.

-- NoteProperty: A property with a static value.

-- ParameterizedProperty: A property that takes parameters and parameter values.

-- Property: A property of the underlying .NET Framework object.

-- PropertySet: A predefined collection of object properties.

-- ScriptMethod: A method whose value is the output of a script.

-- ScriptProperty: A property whose value is the output of a script.

-- All: Gets all member types.

-- Methods: Gets all types of methods of the object (e.g. method, codemethod, scriptmethod)

-- Properties: Gets all types of properties of the object (e.g. property, codeproperty, aliasproperty, scriptproperty).

Not all objects have every type of member. If you specify a member type that the object does not have, Windows PowerShell returns an error.

The Event member type is not valid for Add-Member.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Name <string>

Specifies the name of the member to be added.

If you omit the "Name" parameter name, the value of the -Name parameter must be the second unnamed parameter value in the command. If you include the parameter name, the parameters can appear in any order.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Passes the newly extended object to the pipeline. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SecondValue <Object>

Specifies optional additional information about AliasProperty, ScriptProperty, CodeProperty, or CodeMethod members. If used when adding an AliasProperty, this parameter must be a data type. A conversion (cast) to the specified data type is added to the value of the AliasProperty. For example, if you add an AliasProperty that provides an alternate name for a string property, you can also specify a SecondValue parameter of System.Int32 to indicate that the value of that string property should be converted to an integer when accessed by using the corresponding AliasProperty.

You can use the SecondValue parameter to specify an additional ScriptBlock when adding a ScriptProperty member. In that case, the first ScriptBlock, specified in the Value parameter, is used to get the value of a variable. The second ScriptBlock, specified in the SecondValue parameter, is used to set the value of a variable.

Required? | false
Position? | 4
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Value <Object>

Specifies the initial value of the added member. If you add an AliasProperty, CodeProperty, or CodeMethod member, you can supply optional, additional information by using the SecondValue parameter.

Required? | false
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object type to Add-Member.
Outputs | None or System.Object When you use the PassThru parameter, Add-Member returns the newly-extended object. Otherwise, this cmdlet does not generate any output.

Notes

You can add members only to PSObject objects. To determine if an object is a PSObject object, use the "is" operator. For example, to test an object stored in the $obj variable, type "$obj -is [PSObject]".

The names of the MemberType, Name, Value, and SecondValue parameters are optional. If you omit the parameter names, the unnamed parameter values must appear in this order: MemberType, Name, Value, SecondValue. If you include the parameter names, the parameters can appear in any order

Example 1

C:\PS>$a = (get-childitem)[0]

C:\PS> $a | add-member -membertype noteproperty -name Status -value done

C:\PS> $a | get-member -type noteproperty

TypeName: System.IO.DirectoryInfo

Name          MemberType   Definition
----          ----------   ----------
PSChildName   NoteProperty System.String PSChildName=Co
PSDrive       NoteProperty System.Management.Automation
PSIsContainer NoteProperty System.Boolean PSIsContainer
PSParentPath  NoteProperty System.String PSParentPath=M
PSPath        NoteProperty System.String PSPath=Microso
PSProvider    NoteProperty System.Management.Automation
Status        NoteProperty System.String Status=done

Description
-----------
These commands add the Status note property to a DirectoryInfo object returned by Get-ChildItem and assigns it a value of "done".

The first command gets the first object that Get-Childitem returns (index 0).

The second command adds the note property.

The third command uses a pipeline operator (|) to send the updated object to the Get-Member cmdlet. The output shows that the property has been added.

Example 2

C:\PS>$a = (get-childitem)[0]

C:\PS> $a | add-member -membertype aliasproperty -name FileLength -value Length

C:\PS> $a.filelength

These commands add the FileLength alias property to a DirectoryInfo object returned by Get-ChildItem. The new property is an alias for the Length property.

The first command gets the first object that Get-Childitem returns (index 0).

The second command adds the alias property.

The third command returns the value of the new FileLength property.

Example 3

C:\PS>$a = "a string"

C:\PS> $a = $a | add-member -membertype noteproperty -name StringUse -value Display -passthru

C:\PS> $a.StringUse

These commands add the StringUse a property to a string. Because the string is not a PSObject object, you must include the PassThru parameter in the command to save the extended string in the variable. The last command in the example displays the new property.

Example 4

C:\PS>$a = "this is a string"

C:\PS> $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru

C:\PS> $a.words()

These commands add a script method to a string object. The script method exposes the Split() method of the System.String .NET Framework Class Library class to make it convenient to return the individual words in a string by calling a method named "Words" on the string object. Note that the PassThru parameter is specified to force Add-Member to return the extended string object as output to be stored in the $a variable.

Example 5

C:\PS>$event = get-eventlog -logname system -newest 1

C:\PS> $event.TimeWritten | get-member

C:\PS> add-member -inputobject $event -membertype aliasproperty -name When `
-value TimeWritten -secondvalue System.String

C:\PS> $event.When | get-member

These commands add an AliasProperty to an EventLogEntry object returned by the Get-EventLog cmdlets. The AliasProperty is named "When" and is an alias for the TimeWritten property of the object. The SecondValue parameter is used to specify that the property value should be converted to type System.String when accessed by using the AliasProperty; the TimeWritten property is a DateTime object.

The first command uses the Get-EventLog cmdlet to retrieve the most recent event from the System event log and stores it in the $event variable.

The second command accesses the TimeWritten property of that event and pipes it to the Get-Member cmdlet to demonstrate that the property is a DateTime type. Add-Member is then used to add an AliasProperty member to the instance of the EventLogEntry object stored in the $event variable. The Name parameter is used to set the name of the new member to "When" and the Value parameter is used to specify that it is an alias for the TimeWritten property. The SecondValue parameter is used to indicate that, when this new member is used, the value it returns should be cast from its original System.DateTime type to a System.String type.

The third command accesses the new member and pipes it to the Get-Member cmdlet to confirm that it is of type System.String.

Example 6

C:\PS>function Copy-Property ($From, $To)

{
  foreach ($p in Get-Member -InputObject $From -MemberType Property)
  {
     Add-Member -InputObject $To -MemberType NoteProperty -Name $p.Name
     -Value $From.$($p.Name) -Force

     $To.$($p.Name) = $From.$($p.Name)
   }
}

This function copies all of the properties of one object to another object.

The first command in the function declares the function name and lists its parameters.

The Foreach loop uses the Get-Member cmdlet to get each of the properties of the From object. The commands within the Foreach loop are performed in series on each of the properties.

The Add-Member command adds the property of the From object to the To object as a NoteProperty. It uses the Force parameter to let the command add members with the same member name.

The last command in the function gives the new property the same name as the original property.

See Also

  • Get-Member
  • Export-Clixml
  • Import-Clixml


Add-PSSnapin

Adds one or more Windows PowerShell snap-ins to the current session.

Syntax

Add-PSSnapin [-Name] <string[]> [-PassThru] [<CommonParameters>]

Description

The Add-PSSnapin cmdlet adds registered Windows PowerShell snap-ins to the current session. After the snap-ins are added, you can use the cmdlets and providers that the snap-ins support in the current session.

To add the snap-in to all future Windows PowerShell sessions, add an Add-PSSnapin command to your Windows PowerShell profile. For more information, see about_Profiles.

Parameters

-Name <string[]>

Specifies the name of the snap-in. (This is the Name, not the AssemblyName or ModuleName.)

To find the names of the registered snap-ins on your system, type: "Get-PSSnapin -registered".

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing each added snap-in. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Add-PSSnapin.
Outputs | None or System.Management.Automation.PSSnapInInfo When you use the PassThru parameter, Add-PSSnapin returns a PSSnapInInfo object that represents the snap-in. Otherwise, this cmdlet does not generate any output.

Notes

For detailed information about snap-ins in Windows PowerShell, see about_PSSnapins. For information about how to create a Windows PowerShell snap-in, see "How to Create a Windows PowerShell Snap-in" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=144762.

Add-PSSnapin adds the snap-in only to the current session. To add the snap-in to all Windows PowerShell sessions, add it to your Windows PowerShell profile. For more information, see about_Profiles.

You can add any Windows PowerShell snap-in that has been registered by using the Microsoft .NET Framework install utility. For more information, see "How to Register Cmdlets, Providers, and Host Applications" in the MSDN library at http://go.microsoft.com/fwlink/?LinkID=143619.

To get a list of snap-ins that are registered on your computer, type "Get-PSSnapin -registered".

Before adding a snap-in, Add-PSSnapin checks the version of the snap-in to verify that it is compatible with the current version of Windows PowerShell. If the snap-in fails the version check, Windows PowerShell reports an error.

Example 1

C:\PS>add-PSSnapIn Microsoft.Exchange, Microsoft.Windows.AD

This command adds the Microsoft Exchange and Active Directory snap-ins to the current session.

Example 2

C:\PS>get-pssnapin -registered | add-pssnapin -passthru

This command adds all of the registered Windows PowerShell snap-ins to the session. It uses the Get-PSSnapin cmdlet with the Registered parameter to get objects representing each of the registered snap-ins. The pipeline operator (|) passes the result to Add-PSSnapin, which adds them to the session. The PassThru parameter returns objects that represent each of the added snap-ins.

Example 3

C:\PS>get-pssnapin

This example demonstrates the process of registering a snap-in on your system and then adding it to your session. It uses ManagementFeatures, a fictitious snap-in implemented in a file called ManagementCmdlets.dll.

The first command gets snap-ins that have been added to the current session, including the snap-ins that are installed with Windows PowerShell. In this example, ManagementFeatures is not returned. This indicates that it has not been added to the session.

    get-pssnapin

The second command gets snap-ins that have been registered on your system (including those that have already been added to the session). It does not include the snap-ins that are installed with Windows PowerShell.

    get-pssnapin -registered

In this case, the command does not return any snap-ins. This indicates that the ManagementFeatures snapin has not been registered on the system.

The third command creates an alias, "installutil", for the path to the InstallUtil tool in the .NET Framework.

    set-alias installutil $env:windir\Microsoft.NET\Framework\v2.0.50727\installutil.exe

The fourth command uses the InstallUtil tool to register the snap-in. The command specifies the path to ManagementCmdlets.dll, the file name or "module name" of the snap-in.

    installutil C:\Dev\Management\ManagementCmdlets.dll

The fifth command is the same as the second command. This time, you use it to verify that the ManagementCmdlets snap-in is registered.

    get-pssnapin -registered

The sixth command uses the Add-PSSnapin cmdlet to add the ManagementFeatures snap-in to the session. It specifies the name of the snap-in, ManagementFeatures, not the file name.

    add-pssnapin ManagementFeatures

To verify that the snap-in is added to the session, the seventh command uses the Module parameter of the Get-Command cmdlet. It displays the items that were added to the session by a snap-in or module.

    get-command -module ManagementFeatures

You can also use the PSSnapin property of the object that Get-Command returns to find the snap-in or module in which a cmdlet originated. The eighth command uses dot notation to find the value of the PSSnapin property of the Set-Alias command.

    (get-command set-alias).pssnapin

See Also

  • Get-PSSnapin
  • Remove-PSSnapin
  • about_Profiles


Add-Type

Adds a Microsoft .NET Framework type (a class) to a Windows PowerShell session.

Syntax

Add-Type -AssemblyName <string[]> [-IgnoreWarnings] [-PassThru] [<CommonParameters>]

Add-Type [-Name] <string> [-MemberDefinition] <string[]> [-CodeDomProvider <CodeDomProvider>] [-CompilerParameters <CompilerParameters>] [-Language {<CSharp> | <CSharpVersion3> | <VisualBasic> | <JScript>}] [-Namespace <string>] [-OutputAssembly <string>] [-OutputType <OutputAssemblyType>] [-ReferencedAssemblies <string[]>] [-UsingNamespace <string[]>] [-IgnoreWarnings] [-PassThru] [<CommonParameters>]

Add-Type [-Path] <string[]> [-CompilerParameters <CompilerParameters>] [-OutputAssembly <string>] [-OutputType <OutputAssemblyType>] [-ReferencedAssemblies <string[]>] [-IgnoreWarnings] [-PassThru] [<CommonParameters>]

Add-Type [-TypeDefinition] <string> [-CodeDomProvider <CodeDomProvider>] [-CompilerParameters <CompilerParameters>] [-Language {<CSharp> | <CSharpVersion3> | <VisualBasic> | <JScript>}] [-OutputAssembly <string>] [-OutputType <OutputAssemblyType>] [-ReferencedAssemblies <string[]>] [-IgnoreWarnings] [-PassThru] [<CommonParameters>]

Description

The Add-Type cmdlet lets you define a .NET Framework class in your Windows PowerShell session. You can then instantiate objects (by using the New-Object cmdlet) and use the objects, just as you would use any .NET Framework object. If you add an Add-Type command to your Windows PowerShell profile, the class will be available in all Windows PowerShell sessions.

You can specify the type by specifying an existing assembly or source code files, or you can specify the source code inline or saved in a variable. You can even specify only a method and Add-Type will define and generate the class. You can use this feature to make Platform Invoke (P/Invoke) calls to unmanaged functions in Windows PowerShell. If you specify source code, Add-Type compiles the specified source code and generates an in-memory assembly that contains the new .NET Framework types.

You can use the parameters of Add-Type to specify an alternate language and compiler (CSharp is the default), compiler options, assembly dependencies, the class namespace, the names of the type, and the resulting assembly.

Parameters

-AssemblyName <string[]>

Specifies the name of an assembly that includes the types. Add-Type takes the types from the specified assembly. This parameter is required when you are creating types based on an assembly name.

Enter the full or simple name (also known as the "partial name") of an assembly. Wildcard characters are permitted in the assembly name. If you enter a simple or partial name, Add-Type resolves it to the full name, and then uses the full name to load the assembly.

This parameter does not accept a path or file name. To enter the path to the assembly dynamic-link library (DLL) file, use the Path parameter.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-CodeDomProvider <CodeDomProvider>

Specifies a code generator or compiler. Add-Type uses the specified compiler to compile the source code. The default is the CSharp compiler. Use this parameter if you are using a language that cannot be specified by using the Language parameter. The CodeDomProvider that you specify must be able to generate assemblies from source code.

Required? | false
Position? | named
Default Value | CSharp compiler
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CompilerParameters <CompilerParameters>

Specifies the options for the source code compiler. These options are sent to the compiler without revision.

This parameter allows you to direct the compiler to generate an executable file, embed resources, or set command-line options, such as the "/unsafe" option. This parameter implements the CompilerParameters class (System.CodeDom.Compiler.CompilerParameters).

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-IgnoreWarnings

Ignores compiler warnings. Use this parameter to prevent Add-Type from handling compiler warnings as errors.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Language <Language>

Specifies the language used in the source code. Add-Type uses the language to select the correct code compiler.

Valid values are "CSharp", "CSharpVersion3", "VisualBasic", and "JScript". "CSharp" is the default.

Required? | false
Position? | named
Default Value | CSharp
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MemberDefinition <string[]>

Specifies new properties or methods for the class. Add-Type generates the template code that is required to support the properties or methods.

You can use this feature to make Platform Invoke (P/Invoke) calls to unmanaged functions in Windows PowerShell. For more information, see the examples.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies the name of the class to create. This parameter is required when generating a type from a member definition.

The type name and namespace must be unique within a session. You cannot unload a type or change it. If you need to change the code for a type, you must change the name or start a new Windows PowerShell session. Otherwise, the command fails.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Namespace <string>

Specifies a namespace for the type.

If this parameter is not included in the command, the type is created in the Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes namespace. If the parameter is included in the command with an empty string value or a value of $null, the type is generated in the global namespace.

Required? | false
Position? | named
Default Value | Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OutputAssembly <string>

Generates a DLL file for the assembly with the specified name in the location. Enter a path (optional) and file name. Wildcard characters are permitted. By default, Add-Type generates the assembly only in memory.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-OutputType <OutputAssemblyType>

Specifies the output type of the output assembly. Valid values are Library, ConsoleApplication, and WindowsApplication.

By default, no output type is specified.

This parameter is valid only when an output assembly is specified in the command.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns a System.Runtime object that represents the types that were added. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to source code files or assembly DLL files that contain the types.

If you submit source code files, Add-Type compiles the code in the files and creates an in-memory assembly of the types. The file name extension specified in the value of Path determines the compiler that Add-Type uses.

If you submit an assembly file, Add-Type takes the types from the assembly. To specify an in-memory assembly or the global assembly cache, use the AssemblyName parameter.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ReferencedAssemblies <string[]>

Specifies the assemblies upon which the type depends. By default, Add-Type references System.dll and System.Management.Automation.dll. The assemblies that you specify by using this parameter are referenced in addition to the default assemblies.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-TypeDefinition <string>

Specifies the source code that contains the type definitions. Enter the source code in a string or here-string, or enter a variable that contains the source code. For more information about here-strings, see about_Quoting_Rules.

Include a namespace declaration in your type definition. If you omit the namespace declaration, your type might have the same name as another type or the shortcut for another type, causing an unintentional overwrite. For example, if you define a type called "Exception", scripts that use "Exception" as the shortcut for System.Exception will fail.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UsingNamespace <string[]>

Specifies other namespaces that are required for the class. This is much like the Using keyword in C#.

By default, Add-Type references the System namespace. When the MemberDefinition parameter is used, Add-Type also references the System.Runtime.InteropServices namespace by default. The namespaces that you add by using the UsingNamespace parameter are referenced in addition to the default namespaces.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Add-Type.
Outputs | None or System.RuntimeType When you use the PassThru parameter, Add-Type returns a System.RuntimeType object that represents the new type. Otherwise, this cmdlet does not generate any output.

Notes

The types that you add exist only in the current session. To use the types in all sessions, add them to your Windows PowerShell profile. For more information about the profile, see about_Profiles.

Type names (and namespaces) must be unique within a session. You cannot unload a type or change it. If you need to change the code for a type, you must change the name or start a new Windows PowerShell session. Otherwise, the command fails.

The CodeDomProvider class for some languages, such as IronPython and JSharp, does not generate output. As a result, types written in these languages cannot be used with Add-Type.

This cmdlet is based on the CodeDomProvider class. For more information about this class, see the Microsoft .NET Framework SDK.

Example 1

C:\PS>$source = @"
public class BasicTest
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }

    public int Multiply(int a, int b)
    {
        return (a * b);
    }
}
"@

C:\PS> Add-Type -TypeDefinition $source

C:\PS> [BasicTest]::Add(4, 3)

C:\PS> $basicTestObject = New-Object BasicTest
C:\PS> $basicTestObject.Multiply(5, 2)

These commands add the BasicTest class to the session by specifying source code that is stored in a variable. The type has a static method called Add and a non-static method called Multiply.

The first command stores the source code for the class in the $source variable.

The second command uses the Add-Type cmdlet to add the class to the session. Because it is using inline source code, the command uses the TypeDefinition parameter to specify the code in the $source variable.

The remaining commands use the new class.

The third command calls the Add static method of the BasicTest class. It uses the double-colon characters (::) to specify a static member of the class.

The fourth command uses the New-Object cmdlet to instantiate an instance of the BasicTest class. It saves the new object in the $basicTestObject variable.

The fifth command uses the Multiply method of $basicTestObject.

Example 2

C:\PS>[BasicTest] | get-member

C:\PS> [BasicTest] | get-member -static

C:\PS> $basicTestObject | get-member

C:\PS> [BasicTest] | get-member

   TypeName: System.RuntimeType

Name                           MemberType Definition
----                           ---------- ----------
Clone                          Method     System.Object Clone()
Equals                         Method     System.Boolean Equals
FindInterfaces                 Method     System.Type[] FindInt
...

C:\PS> [BasicTest] | get-member -static

   TypeName: BasicTest

Name            MemberType Definition
----            ---------- ----------
Add             Method     static System.Int32 Add(Int32 a, Int32 b)
Equals          Method     static System.Boolean Equals(Object objA,
ReferenceEquals Method     static System.Boolean ReferenceEquals(Obj

C:\PS> $basicTestObject | get-member

   TypeName: BasicTest

Name        MemberType Definition
----        ---------- ----------
Equals      Method     System.Boolean Equals(Object obj)
GetHashCode Method     System.Int32 GetHashCode()
GetType     Method     System.Type GetType()
Multiply    Method     System.Int32 Multiply(Int32 a, Int32 b)
ToString    Method     System.String ToString()

Description
-----------
These commands use the Get-Member cmdlet to examine the objects that the Add-Type and New-Object cmdlets created in the previous example.

The first command uses the Get-Member cmdlet to get the type and members of the BasicTest class that Add-Type added to the session. The Get-Member command reveals that it is a System.RuntimeType object, which is derived from the System.Object class.

The second command uses the Static parameter of Get-Member to get the static properties and methods of the BasicTest class. The output shows that the Add method is included.

The third command uses Get-Member to get the members of the object stored in the $BasicTestObject variable. This was the object instance that was created by using the New-Object cmdlet with the $BasicType class.

The output reveals that the value of the $basicTestObject variable is an instance of the BasicTest class and that it includes a member called Multiply.

Example 3

C:\PS>$accType = add-type -assemblyname accessib* -passthru

This command adds the classes from the Accessibility assembly to the current session. The command uses the AssemblyName parameter to specify the name of the assembly. The wildcard character allows you to get the correct assembly even when you are not sure of the name or its spelling.

The command uses the PassThru parameter to generate objects that represent the classes that are added to the session, and it saves the objects in the $accType variable.

Example 4

C:\PS>add-type -path c:\ps-test\Hello.vb

[VBFromFile]::SayHello(", World")

# From Hello.vb
Public Class VBFromFile

Public Shared Function SayHello(sourceName As String) As String
Dim myValue As String = "Hello"

return myValue + sourceName
End Function
End Class

C:\PS> [VBFromFile]::SayHello(", World")
Hello, World

Description
-----------
This example uses the Add-Type cmdlet to add the VBFromFile class that is defined in the Hello.vb file to the current session. The text of the Hello.vb file is shown in the command output.

The first command uses the Add-Type cmdlet to add the type defined in the Hello.vb file to the current session. The command uses the path parameter to specify the source file.

The second command calls the SayHello function as a static method of the VBFromFile class.

Example 5

C:\PS>$signature = @"
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
"@

$showWindowAsync = Add-Type -memberDefinition $signature -name "Win32ShowWindowAsync" -namespace Win32Functions -passThru

# Minimize the Windows PowerShell console
$showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 2)

# Restore it
$showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 4)

The commands in this example demonstrate how to call native Windows APIs in Windows PowerShell. Add-Type uses the Platform Invoke (P/Invoke) mechanism to call a function in User32.dll from Windows PowerShell.

The first command stores the C# signature of the ShowWindowAsync function in the $signature variable. (For more information, see "ShowWindowAsync Function" in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=143643.) To ensure that the resulting method will be visible in a Windows PowerShell session, the "public" keyword has been added to the standard signature.

The second command uses the Add-Type cmdlet to add the ShowWindowAsync function to the Windows PowerShell session as a static method of a class that Add-Type creates. The command uses the MemberDefinition parameter to specify the method definition saved in the $signature variable.

The command uses the Name and Namespace parameters to specify a name and namespace for the class. It uses the PassThru parameter to generate an object that represents the types, and it saves the object in the $showWindowAsync variable.

The third and fourth commands use the new ShowWindowAsync static method. The method takes two parameters, the window handle, and an integer specifies how the window is to be shown.

The third command calls ShowWindowAsync. It uses the Get-Process cmdlet with the $pid automatic variable to get the process that is hosting the current Windows PowerShell session. Then it uses the MainWindowHandle property of the current process and a value of "2", which represents the SW_MINIMIZE value.

To restore the window, the fourth command use a value of "4" for the window position, which represents the SW_RESTORE value. (SW_MAXIMIZE is 3.)

Example 6

C:\PS>Add-Type -MemberDefinition $jsMethod -Name "PrintInfo" -Language JScript

This command uses the Add-Type cmdlet to add a method from inline JScript code to the Windows PowerShell session. It uses the MemberDefinition parameter to submit source code stored in the $jsMethod variable. It uses the Name variable to specify a name for the class that Add-Type creates for the method and the Language parameter to specify the JScript language.

Example 7

C:\PS>Add-Type -Path FSharp.Compiler.CodeDom.dll

C:\PS> Add-Type -Path FSharp.Compiler.CodeDom.dll
C:\PS> $provider = New-Object Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider

C:\PS> $fSharpCode = @"
let rec loop n =
if n <= 0 then () else begin
print_endline (string_of_int n);
loop (n-1)
end
"@

C:\PS> $fsharpType = Add-Type -TypeDefinition $fSharpCode -CodeDomProvider $provider -PassThru | where { $_.IsPublic }
C:\PS> $fsharpType::loop(4)
4
3
2
1

Description
-----------
This example shows how to use the Add-Type cmdlet to add an FSharp code compiler to your Windows PowerShell session. To run this example in Windows PowerShell, you must have the FSharp.Compiler.CodeDom.dll that is installed with the FSharp language.

The first command in the example uses the Add-Type cmdlet with the Path parameter to specify an assembly. Add-Type gets the types in the assembly.

The second command uses the New-Object cmdlet to create an instance of the FSharp code provider and saves the result in the $provider variable.

The third command saves the FSharp code that defines the Loop method in the $FSharpCode variable.

The fourth command uses the Add-Type cmdlet to save the public types defined in $fSharpCode in the $fSharpType variable. The TypeDefinition parameter specifies the source code that defines the types. The CodeDomProvider parameter specifies the source code compiler.

The PassThru parameter directs Add-Type to return a Runtime object that represents the types and a pipeline operator (|) sends the Runtime object to the Where-Object cmdlet, which returns only the public types. The Where-Object filter is used because the FSharp provider generates non-public types to support the resulting public type.

The fifth command calls the Loop method as a static method of the type stored in the $fSharpType variable.

See Also

  • Add-Member
  • New-Object


Checkpoint-Computer

Creates a system restore point on the local computer.

Syntax

Checkpoint-Computer [-Description] <string> [[-RestorePointType] <string>] [<CommonParameters>]

Description

The Checkpoint-Computer cmdlet creates a system restore point on the local computer. This cmdlet runs only on Windows Vista and Windows XP.

Parameters

-Description <string>

Specifies a descriptive name for the restore point. This parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RestorePointType <string>

Specifies the type of restore point. The default is APPLICATION_INSTALL.

Valid values are APPLICATION_INSTALL, APPLICATION_UNINSTALL, DEVICE_DRIVER_INSTALL, MODIFY_SETTINGS, and CANCELLED_OPERATION.

Required? | false
Position? | 2
Default Value | APPLICATION_INSTALL
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Checkpoint-Computer.
Outputs | None This cmdlet does not generate any output.

Notes

This cmdlet uses the CreateRestorePoint method of the SystemRestore class with a BEGIN_SYSTEM_CHANGE event.

Example 1

C:\PS>checkpoint-computer -description "Install MyApp"

This command creates a system restore point called "Install MyApp". It uses the default APPLICATION_INSTALL restore point type.

Example 2

C:\PS>checkpoint-computer -description "ChangeNetSettings" -RestorePointType MODIFY_SETTINGS

This command creates a MODIFY_SETTINGS system restore point called "ChangeNetSettings".

See Also

  • Add-Computer
  • Remove-Computer
  • Restart-Computer
  • Restore-Computer
  • Stop-Computer
  • Test-Connection


Clear-Content

Deletes the contents of an item, such as deleting the text from a file, but does not delete the item.

Syntax

Clear-Content [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Clear-Content [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Clear-Content cmdlet deletes the contents of an item, such as deleting the text from a file, but it does not delete the item. As a result, the item exists, but it is empty. Clear-Content is similar to Clear-Item, but it works on files instead of on aliases and variables.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to clear the file contents even if the file is read-only. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Clears only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the paths to the items from which content is deleted. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the paths to the items from which content is deleted. Wildcards are permitted. The paths must be paths to items, not to containers. For example, you must specify a path to one or more files, not a path to a directory. Wildcards are permitted. This parameter is required, but the parameter name ("Path") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Clear-Content.
Outputs | None This cmdlet does not return any objects.

Notes

You can also refer to Clear-Content by its built-in alias, "clc". For more information, see about_Aliases.

If you omit the -Path parameter name, the value of Path must be the first parameter in the command. For example, "clear-content c:\mydir\*.txt". If you include the parameter name, you can list the parameters in any order.

You can use Clear-Content with the Windows PowerShell File System provider and with other providers that manipulate content. To clear items that are not considered to be content, such as items managed by the Windows PowerShell Certificate or Registry providers, use Clear-Item.

The Clear-Content cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>clear-content ..\SmpUsers\*\init.txt

This command deletes all of the content from the "init.txt" files in all subdirectories of the SmpUsers directory. The files are not deleted, but they are empty.

Example 2

C:\PS>clear-content -path * -filter *.log -force

This command deletes the contents of all files in the current directory with the ".log" file name extension, including files with the read-only attribute. The asterisk (*) in the path represents all items in the current directory. The Force parameter makes the command effective on read-only files. Using a filter to restrict the command to files with the ".log" file name extension instead of specifying "*.log" in the path makes the operation faster.

Example 3

C:\PS>clear-content c:\Temp\* -Include Smp* -Exclude *2* -whatif

This command requests a prediction of what would happen if you submitted the command: "clear-content c:\temp\* -include smp* -exclude *2*". The result lists the files that would be cleared; in this case, files in the Temp directory whose names begin with "Smp", unless the file names include a "2". To execute the command, run it again without the Whatif parameter.

See Also

  • about_Providers
  • Get-Content
  • Set-Content
  • Add-Content
  • Get-Item


Clear-EventLog

Deletes all entries from specified event logs on the local or remote computers.

Syntax

Clear-EventLog [-LogName] <string[]> [[-ComputerName] <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Clear-EventLog cmdlet deletes all of the entries from the specified event logs on the local computer or on remote computers. To use Clear-EventLog, you must be a member of the Administrators group on the affected computer.

The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.

Parameters

-ComputerName <string[]>

Specifies a remote computer. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-EventLog even if your computer is not configured to run remote commands.

Required? | false
Position? | 2
Default Value | Local computer
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-LogName <string[]>

Specifies the event logs. Enter the log name (the value of the Log property; not the LogDisplayName) of one or more event logs, separated by commas. Wildcard characters are not permitted. This parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Clear-EventLog.
Outputs | None This cmdlet does not generate any output.

Notes

To use Clear-EventLog on Windows Vista and later versions of Windows, start Windows PowerShell with the "Run as administrator" option.

Example 1

C:\PS>clear-eventlog "Windows PowerShell"

This command deletes the entries from the "Windows PowerShell" event log on the local computer.

Example 2

C:\PS>clear-eventlog -logname ODiag, OSession -computername localhost, Server02

This command deletes all of the entries in the Microsoft Office Diagnostics (ODiag) and Microsoft Office Sessions (OSession) logs on the local computer and the Server02 remote computer.

Example 3

C:\PS>clear-eventlog -log application, system -confirm

This command prompts you for confirmation before deleting the entries in the specified event logs.

Example 4

C:\PS>function clear-all-event-logs ($computerName="localhost")
{
    $logs = get-eventlog -computername $computername -list | foreach {$_.Log}
    $logs | foreach {clear-eventlog -comp $computername -log $_ }
    get-eventlog -computername $computername -list
}

C:\PS> clear-all-event-logs -comp Server01

Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  15,168      0 OverwriteAsNeeded           0 Application
  15,168      0 OverwriteAsNeeded           0 DFS Replication
     512      7 OverwriteOlder              0 DxStudio
  20,480      0 OverwriteAsNeeded           0 Hardware Events
     512      7 OverwriteOlder              0 Internet Explorer
  20,480      0 OverwriteAsNeeded           0 Key Management Service
  16,384      0 OverwriteAsNeeded           0 Microsoft Office Diagnostics
  16,384      0 OverwriteAsNeeded           0 Microsoft Office Sessions
  30,016      0 OverwriteAsNeeded           1 Security
  15,168      0 OverwriteAsNeeded           2 System
  15,360      0 OverwriteAsNeeded           0 Windows PowerShell

Description
-----------
This function clears all event logs on the specified computers and then displays the resulting event log list.

Notice that a few entries were added to the System and Security logs after the logs were cleared but before they were displayed.

See Also

  • Get-EventLog
  • Limit-EventLog
  • New-EventLog
  • Remove-EventLog
  • Show-Eventlog
  • Write-EventLog
  • Get-WinEvent


Clear-History

Deletes entries from the command history.

Syntax

Clear-History [[-Id] <Int32[]>] [[-Count] <int>] [-Newest] [-Confirm] [-WhatIf] [<CommonParameters>]

Clear-History [[-Count] <int>] [-CommandLine <string[]>] [-Newest] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Clear-History cmdlet deletes commands from the command history, that is, the list of commands entered during the current session.

Without parameters, Clear-History deletes all commands from the session history, but you can use the parameters of Clear-History to delete selected commands.

Parameters

-CommandLine <string[]>

Deletes commands with the specified text strings. If you enter more than one string, Clear-History deletes commands with any of the strings.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Count <int>

Clears the specified number of history entries, beginning with the oldest entry in the history.

If you use the Count and Id parameters in the same command, the cmdlet clears the number of entries specified by the Count parameter, beginning with the entry specified by the Id parameter. For example, if Count is 10 and Id is 30, Clear-History clears items 21 through 30 inclusive.

If you use the Count and CommandLine parameters in the same command, Clear-History clears the number of entries specified by the Count parameter, beginning with the entry specified by the CommandLine parameter.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Id <Int32[]>

Deletes commands with the specified history IDs.

To find the history ID of a command, use Get-History.

Required? | false
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Newest

Deletes the newest entries in the history. By default, Clear-History deletes the oldest entries in the history.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Clear-History.
Outputs | None This cmdlet does not generate any output.

Notes

The session history is a list of the commands entered during the session. You can view the history, add and delete commands, and run commands from the history. For more information, see about_History.

Deleting a command from the history does not change the history IDs of the remaining items in the command history.

Example 1

C:\PS>clear-history

Deletes all commands from the session history.

Example 2

C:\PS>clear-history -id 23, 25

Deletes the commands with history IDs 23 and 25.

Example 3

C:\PS>clear-history -command *help*, *command

Deletes commands that include "help" or end in "command".

Example 4

C:\PS>clear-history -count 10 -newest

Deletes the 10 newest commands from the history.

Example 5

C:\PS>clear-history -id 10 -count 3

Deletes the three oldest commands, beginning with the entry with ID 10.

See Also

  • about_History
  • Get-History
  • Add-History
  • Invoke-History


Clear-Item

Deletes the contents of an item, but does not delete the item.

Syntax

Clear-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Clear-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Clear-Item cmdlet deletes the value of an item, but it does not delete the item. For example, Clear-Item can delete the value of a variable, but it does not delete the variable. The value that used to represent a cleared item is defined by each Windows PowerShell provider. Clear-Item is similar to Clear-Content, but it works on aliases and variables, instead of files.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to clear items that cannot otherwise be changed, such as read- only aliases. The cmdlet cannot clear constants. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Clears only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the path to the items being cleared. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the items being cleared. Wildcards are permitted. This parameter is required, but the parameter name ("Path") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a path string to Clear-Item.
Outputs | None This cmdlet does not return any objects.

Notes

The Clear-Item cmdlet is supported only by several Windows PowerShell providers, including the Alias, Environment, Function, Registry, and Variable providers. As such, you can use Clear-Item to delete the content of items in the provider namespaces.

You cannot use Clear-Item to delete the contents of a file, because the Windows PowerShell FileSystem Provider does not support this cmdlet. To clear files, use Clear-Content.

You can also refer to Clear-Item by its built-in alias, "cli". For more information, type "Get-Help about_Aliases".

The Clear-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>clear-item Variable:TestVar1

This command deletes the value of the variable, Testvar1. The variable remains and is valid, but its value is set to null.

The variable name is prefixed with "Variable:" to indicate the Windows PowerShell Variable provider. To get the same result, you can switch to the Windows PowerShell Variable provider namespace first and then perform the Clear-Item command.

    PS C:> Set-location Variable:
    PS Variable:\> clear-item Testvar1

Example 2

C:\PS>clear-item Alias:log* -include *1* -exclude *3* -whatif

What if: Performing operation "Clear Item" on Target "Item: log1".

Description
-----------
This command asks Windows PowerShell what would happen if you executed the command, "clear-item alias:log* -include *1* -exclude *3". In response, Windows PowerShell explains that it would delete the value of the log1 alias.

This command would not have any effect on the log, log2, or log13 aliases. Because the Alias provider does not permit an alias without a value, when you clear an alias, you also delete the alias.

Example 3

C:\PS>clear-item registry::HKLM\Software\MyCompany\MyKey -confirm

This command deletes all registry entries in the MyKey subkey, but only after prompting you to confirm your intent. It does not delete the MyKey subkey or affect any other registry keys or entries. You can use the Include and Exclude parameters to identify particular registry keys, but you cannot use them to identify registry entries. To delete particular registry entries, use Remove-ItemProperty. To delete the value of a registry entry, use Clear-ItemProperty.

See Also

  • about_Providers
  • Copy-Item
  • Get-Item
  • Invoke-Item
  • Move-Item
  • Set-Item
  • New-Item
  • Remove-Item
  • Rename-Item


Clear-ItemProperty

Deletes the value of a property but does not delete the property.

Syntax

Clear-ItemProperty [-LiteralPath] <string[]> [-Name] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Clear-ItemProperty [-Path] <string[]> [-Name] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Clear-ItemProperty cmdlet deletes the value of a property, but it does not delete the property. You can use this cmdlet to delete the data from a registry value.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt" or "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to delete properties from items that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see about_Providers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Clears only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the path to the property being cleared. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string>

Specifies the name of the property to be cleared, such as the name of a registry value. Wildcards are not permitted.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the cleared item's property. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the property being cleared. Wildcards are permitted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a path string to Clear-ItemProperty.
Outputs | None or System.Management.Automation.PSCustomObject When you use the PassThru parameter, Clear-ItemProperty generates a PSCustomObject object that represents the cleared item property. Otherwise, this cmdlet does not generate any output.

Notes

You can use Clear-ItemProperty to delete the data in registry values without deleting the value. If the data type of the value is Binary or DWORD, clearing the data sets the value to zero. Otherwise, the value is empty.

You can also refer to Clear-ItemProperty by its built-in alias, "clp". For more information, see about_Aliases.

The Clear-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>clear-itemproperty -path HKLM:\Software\MyCompany\MyApp -name Options

This command deletes the data in the Options registry value in the MyApp subkey of HKEY_LOCAL_MACHINE\Software\MyCompany.

Because the command is being issued from a file system drive (C:), it uses the fully qualified path to the HKLM: drive and the Software\MyCompany\MyApp subkey. It uses the Name parameter to specify the Options value.

See Also

  • about_Providers
  • Copy-ItemProperty
  • New-ItemProperty
  • Move-ItemProperty
  • Rename-ItemProperty
  • Get-ItemProperty
  • New-ItemProperty


Clear-Variable

Deletes the value of a variable.

Syntax

Clear-Variable [-Name] <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Clear-Variable cmdlet deletes the data stored in a variable, but it does not delete the variable. As a result, the value of the variable is NULL (empty). If the variable has a specified data or object type, Clear-Variable preserves the type of the object stored in the variable.

Parameters

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to clear a variable even if it is read-only. Even using the Force parameter, the cmdlet cannot clear constants.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Clears only the specified items. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the name of the variable to be cleared. Wildcards are permitted. This parameter is required, but the parameter name ("Name") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the cleared variable. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Scope <string>

Specifies the scope in which this alias is valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Clear-Variable.
Outputs | None or System.Management.Automation.PSVariable When you use the PassThru parameter, Clear-Variable generates a System.Management.Automation.PSVariable object representing the cleared variable. Otherwise, this cmdlet does not generate any output.

Notes

To delete a variable, along with its value, use Remove-Variable or Remove-Item.

Clear-Variable will not delete the values of variables that are set as constants or owned by the system, even if you use the -Force parameter.

If the variable that you are clearing does not exist, the cmdlet has no effect. It does not create a variable with a null value.

You can also refer to Clear-Variable by its built-in alias, "clv". For more information, see about_Aliases.

Example 1

C:\PS>clear-variable my* -global

This command deletes the value of the global variables that begin with "my".

Example 2

C:\PS>$a=3

C:\PS>&{ clear-variable a }

C:\PS>$a
3

These commands demonstrate that clearing a variable in a child scope does not clear the value in the parent scope. The first command sets the value of the variable $a to "3". The second command uses the invoke operator (&) to run a Clear-Variable command in a new scope. The variable is cleared in the child scope (although it did not exist), but it is not cleared in the local scope. The third command, which gets the value of $a, shows that the value "3" is unaffected.

Example 3

C:\PS>clear-variable -name processes

This command deletes the value of the $processes variable. The $processes variable still exists, but the value is null.

See Also

  • Get-Variable
  • Set-Variable
  • New-Variable
  • Remove-Variable


Compare-Object

Compares two sets of objects.

Syntax

Compare-Object [-ReferenceObject] <PSObject[]> [-DifferenceObject] <PSObject[]> [-CaseSensitive] [-Culture <string>] [-ExcludeDifferent] [-IncludeEqual] [-PassThru] [-Property <Object[]>] [-SyncWindow <int>] [<CommonParameters>]

Description

The Compare-Object cmdlet compares two sets of objects. One set of objects is the Reference set, and the other set is the Difference set.

The result of the comparison indicates whether a property value appeared only in the object from the Reference set (indicated by the <= symbol), only in the object from the Difference set (indicated by the => symbol) or, if the IncludeEqual parameter is specified, in both objects (indicated by the == symbol).

Parameters

-CaseSensitive

Indicates that comparisons should be case-sensitive.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Culture <string>

Specifies the culture to use for comparisons.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DifferenceObject <PSObject[]>

Specifies the objects that are compared to the reference objects.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-ExcludeDifferent

Displays only the characteristics of compared objects that are equal.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-IncludeEqual

Displays characteristics of compared objects that are equal. By default, only characteristics that differ between the reference and difference objects are displayed.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Passes the objects that differed to the pipeline. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Property <Object[]>

Specifies the properties of the reference and difference objects to compare.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ReferenceObject <PSObject[]>

Objects used as a reference for comparison.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SyncWindow <int>

Defines a search region in which an attempt is made to re-synchronize the order if there is no match. The default value is [Int32]::MaxValue.

Required? | false
Position? | named
Default Value | [Int32]::MaxValue
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe a DifferenceObject object to Compare-Object.
Outputs | None, or the objects that are different When you use the PassThru parameter, Compare-Object returns the objects that differed. Otherwise, this cmdlet does not generate any output.

Example 1

C:\PS>compare-object -referenceobject $(get-content C:\test\testfile1.txt) -differenceobject $(get-content C:\test\testfile2.txt)

This command compares the contents of two text files. It displays only the lines that appear in one file or in the other file, not lines that appear in both files.

Example 2

C:\PS>compare-object -referenceobject $(get-content C:\Test\testfile1.txt) -differenceobject $(get-content C:\Test\testfile2.txt) -includeequal

This command compares each line of content in two text files. It displays all lines of content from both files, indicating whether each line appears in only Textfile1.txt or Textfile2.txt or whether each line appears in both files.

Example 3

C:\PS>$processes_before = get-process

C:\PS> notepad

C:\PS> $processes_after  = get-process

C:\PS> compare-object -referenceobject $processes_before -differenceobject $processes_after

These commands compare two sets of process objects.

The first command uses the Get-Process cmdlet to get the processes on the computer. It stores them in the $processes_before variable.

The second command starts Notepad.

The third command uses the Get-Process cmdlet again and stores the resulting processes in the $processes_after variable.

The fourth command uses the Compare-Object cmdlet to compare the two sets of process objects. It displaysthe differences between them, which include the new instance of Notepad.

See Also

  • Group-Object
  • Measure-Object
  • Sort-Object
  • ForEach-Object
  • New-Object
  • Select-Object
  • Tee-Object
  • Where-Object


Complete-Transaction

Commits the active transaction.

Syntax

Complete-Transaction [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Complete-Transaction cmdlet commits an active transaction. When you commit a transaction, the commands in the transaction are finalized and the data affected by the commands is changed.

If the transaction includes multiple subscribers, to commit the transaction, you must enter one Complete-Transaction command for every Start-Transaction command.

The Complete-Transaction cmdlet is one of a set of cmdlets that support the transactions feature in Windows PowerShell. For more information, see about_Transactions.

Parameters

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Complete-Transaction.
Outputs | None This cmdlet does not return any objects.

Notes

You cannot roll back a transaction that has been committed, or commit a transaction that has been rolled back.

You cannot roll back any transaction other than the active transaction. To roll back a different transaction, you must first commit or roll back the active transaction.

By default, if any part of a transaction cannot be committed, such as when a command in the transaction results in an error, the entire transaction is rolled back.

Example 1

C:\PS>cd hkcu:\software

PS HKCU:\software> start-transaction

PS HKCU:\software> new-item MyCompany -UseTransaction
PS HKCU:\software> dir m*

   Hive: HKEY_CURRENT_USER\software

SKC  VC Name                           Property
---  -- ----                           --------
 82   1 Microsoft                      {(default)}

PS HKCU:\software> complete-transaction
PS HKCU:\software> dir m*

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
 82   1 Microsoft                      {(default)}
  0   0 MyCompany                      {}

Description
-----------
This example shows the effect of using the Complete-Transaction cmdlet to commit a transaction.

The Start-Transaction command starts the transaction. The New-Item command uses the UseTransaction parameter to include the command in the transaction.

The first "dir" (Get-ChildItem) command shows that the new item has not yet been added to the registry.

The Complete-Transaction command commits the transaction, which makes the registry change effective. As a result, the second "dir" command shows that the registry is changed.

Example 2

C:\PS>cd hkcu:\software

PS HKCU:\software> start-transaction
PS HKCU:\software> new-item MyCompany -UseTransaction

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
  0   0 MyCompany                      {}

PS HKCU:\software> start-transaction
PS HKCU:\Software> Get-Transaction

RollbackPreference   SubscriberCount  Status
------------------   ---------------  ------
Error                2                Active

PS HKCU:\software> new-itemproperty -path MyCompany -name MyKey -value -UseTransaction

MyKey
-----
123

PS HKCU:\software> complete-transaction
PS HKCU:\software> get-transaction

RollbackPreference   SubscriberCount  Status
------------------   ---------------  ------
Error                1                Active

PS HKCU:\software> dir m*

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
 82   1 Microsoft                      {(default)}

PS HKCU:\software> complete-transaction
PS HKCU:\software> dir m*

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
 82   1 Microsoft                      {(default)}
  0   1 MyCompany                      {MyKey}

Description
-----------
This example shows how to use Complete-Transaction to commit a transaction that has more than one subscriber.

To commit a multi-subscriber transaction, you must enter one Complete-Transaction command for every Start-Transaction command. The data is changed only when the final Complete-Transaction command is submitted.

For demonstration purposes, this example shows a series of commands entered at the command line. In practice, transactions are likely to be run in scripts, with the secondary transaction being run by a function or helper script that is called by the main script.

In this example, a Start-Transaction command starts the transaction. A New-Item command with the UseTransaction parameter adds the MyCompany key to the Software key. Although the New-Item command returns a key object, the data in the registry is not yet changed.

A second Start-Transaction command adds a second subscriber to the existing transaction. The Get-Transaction command confirms that the subscriber count is 2. A New-ItemProperty command with the UseTransaction parameter adds a registry entry to the new MyCompany key. Again, the command returns a value, but the registry is not changed.

The first Complete-Transaction command reduces the subscriber count by 1. This is confirmed by a Get-Transaction command. However, no data is changed, as evidenced by a "dir m*" (Get-ChildItem) command.

The second Complete-Transaction command commits the entire transaction and changes the data in the registry. This is confirmed by a second "dir m*" command, which shows the changes.

Example 3

C:\PS>cd hkcu:\software

PS HKCU:\software> start-transaction

PS HKCU:\software> new-item MyCompany -UseTransaction

PS HKCU:\software> dir m*

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
 82   1 Microsoft                      {(default)}

PS HKCU:\software> dir m* -UseTransaction

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
 82   1 Microsoft                      {(default)}
  0   0 MyCompany                      {}

PS HKCU:\software> complete-transaction

Description
-----------
This example shows the value of using Get-* commands, and other commands that do not change data, in a transaction. When a Get-* command is used in a transaction, it gets the objects that are part of the transaction. This allows you to preview the changes in the transaction before the changes are committed.

In this example, a transaction is started. A New-Item command with the UseTransaction parameter adds a new key to the registry as part of the transaction.

Because the new registry key is not added to the registry until the Complete-Transaction command is run, a simple "dir" (Get-ChildItem) command shows the registry without the new key.

However, when you add the UseTransaction parameter to the "dir" command, the command becomes part of the transaction, and it gets the items in the transaction even if they are not yet added to the data.

See Also

  • about_Transactions
  • Start-Transaction
  • Get-Transaction
  • Undo-Transaction
  • Use-Transaction


Connect-WSMan

Connects to the WinRM service on a remote computer.

Syntax

Connect-WSMan [-ApplicationName <string>] [-ComputerName <string>] [-Port <int>] [-UseSSL] [-Authentication <Authentication>] [-ComputerName <string>] [-Credential <PSCredential>] [-Port <int>] [-SessionOption <hashtable>] [<CommonParameters>]

Connect-WSMan [-ConnectionURI <Uri>] [-Authentication <Authentication>] [-ComputerName <string>] [-Credential <PSCredential>] [-Port <int>] [-SessionOption <hashtable>] [<CommonParameters>]

Description

The Connect-WSMan cmdlet connects to the WinRM service on a remote computer, and it establishes a persistent connection to the remote computer. You can use this cmdlet within the context of the WS-Management Provider to connect to the WinRM service on a remote computer. However, you can also use this cmdlet to connect to the WinRM service on a remote computer before you change to the WS-Management Provider. The remote computer will appear in the root directory of the WS-Management Provider.

For more information about how to disconnect from the WinRM service on a remote computer, see Disconnect-WSMan.

Parameters

-ApplicationName <string>

Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for the remote endpoint is in the following format:

<transport>://<server>:<port>/<ApplicationName>

For example:

http://server01:8080/WSMAN

Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency.

Required? | false
Position? | named
Default Value | wsman
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <Authentication>

Specifies the authentication mechanism to be used at the server. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.

- Default : Use the authentication method implemented by the WS-Management protocol. This is the default.

- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

- Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates.

- Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.

- CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

Caution: CredSSP delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

Required? | false
Position? | named
Default Value | Default
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

Required? | false
Position? | named
Default Value | localhost
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ConnectionURI <Uri>

Specifies the connection endpoint. The format of this string is:

<Transport>://<Server>:<Port>/<ApplicationName>.

The following string is a properly formatted value for this parameter:

http://Server01:8080/WSMAN. The URI must be fully qualified .

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Domain.com". Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OptionSet <hashtable>

Passes a set of switches to the service to modify or refine the nature of the request. These are similar to switches used in command-line shells in that they are service specific. Any number of options can be specified.

The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters:

-OptionSet @{a=1;b=2;c=3}

Required? |
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Port <int>

Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server's certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted computers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SessionOption <hashtable>

Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, see New-WSManSessionOption.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Notes

You can run management commands or query management data on a remote computer without creating a WS-Management session. You can do this by using the ComputerName parameters of Invoke-WSManAction and Get-WSManInstance. When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used for the single command. After the command runs, the connection is closed.

Example 1

C:\PS>Connect-WSMan -computer server01

PS C:\Users\testuser> cd wsman:
PS WSMan:\>
PS WSMan:\> dir

   WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName                                  Type
------------                                  ----
localhost                                     Container
server01                                      Container

Description
-----------
This command creates a connection to the remote server01 computer.

The Connect-WSMan cmdlet is generally used within the context of the WS-Management provider to connect to a remote computer, in this case the server01 computer. However, you can use the cmdlet to establish connections to remote computers before you change to the WS-Management provider. Those connections will appear in the ComputerName list.

Example 2

C:\PS>$cred = Get-Credential Administrator
Connect-WSMan -computer server01 -credential $cred

PS C:\Users\testuser> cd wsman:
PS WSMan:\>
PS WSMan:\> dir

   WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName                                  Type
------------                                  ----
localhost                                     Container
server01                                      Container

Description
-----------
This command creates a connection to the remote system server01 using the Administrator account credentials.

The first command uses the Get-Credential cmdlet to get the Administrator credentials and then stores them in the $cred variable.  The Get-Credential cmdlet prompts the user for a password of username and password. Users are prompted throught a dialog box
or at the command line, depending on system registry settings.

The second command uses the Credential parameter to pass the credentials stored in $cred to Connect-WSMan. Connect-WSMan then connects to the remote system server01 using the Administrator credentials.

The Connect-WSMan cmdlet is generally used within the context of the WS-Management provider to connect to a remote computer, in this case server01. However, the cmdlet can be used establish connections to remote computers before changing to the WS-Management provider and those connections will show up in the ComputerName list.

Example 3

C:\PS>Connect-WSMan -computer server01 -port 80

PS C:\Users\testuser> cd wsman:
PS WSMan:\>
PS WSMan:\> dir

   WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName                                  Type
------------                                  ----
localhost                                     Container
server01                                      Container

Description
-----------
This command creates a connection to the remote server01 computer over port 80.

The Connect-WSMan cmdlet is generally used within the context of the WS-Management provider to connect to a remote computer, in this case the server01 computer. However, you can use the cmdlet to establish connections to remote computers before you change to the WS-Management provider. Those connections will appear in the ComputerName list.

Example 4

C:\PS>$a = New-WSManSessionOption -operationtimeout 30000
Connect-WSMan -computer server01 -sessionoption $a

PS C:\Users\testuser> cd wsman:
PS WSMan:\>
PS WSMan:\> dir

   WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName                                  Type
------------                                  ----
localhost                                     Container
server01                                      Container

Description
-----------
This command creates a connection to the remote server01 computer by using the connection options that are defined in the New-WSManSessionOption command.

The first command uses the New-WSManSessionOption cmdlet to store a set of connection setting options in the $a variable. In this case, the session options set a connection time out of 30 seconds (30,000 milliseconds).

The second command uses the SessionOption parameter to pass the credentials that are stored in the $a variable to Connect-WSMan. Then, Connect-WSMan connects to the remote server01 computer by using the specified session options.

The Connect-WSMan cmdlet is generally used within the context of the WS-Management provider to connect to a remote computer, in this case the server01 computer. However, you can use the cmdlet to establish connections to remote computers before you change to the WS-Management provider. Those connections will appear in the ComputerName list.

See Also

  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


ConvertFrom-CSV

Converts object properties in comma-separated value (CSV) format into CSV versions of the original objects.

Syntax

ConvertFrom-CSV [[-Delimiter] <char>] [-InputObject] <PSObject[]> [-Header <string[]>] [<CommonParameters>]

ConvertFrom-CSV -UseCulture [-InputObject] <PSObject[]> [-Header <string[]>] [<CommonParameters>]

Description

The ConvertFrom-CSV cmdlet creates objects from CSV variable-length strings that are generated by the ConvertTo-CSV cmdlet.

You can use the parameters of the ConvertFrom-CSV cmdlet to specify the column header row, which determines the property names of the resulting objects, to specify the item delimiter, or to direct ConvertFrom-CSV to use the list separator for the current culture as the delimiter.

The objects that ConvertFrom-CSV creates are CSV versions of the original objects. The property values of the CSV objects are string versions of the property values of the original objects. The CSV versions of the objects do not have any methods.

You can also use the Export-CSV and Import-CSV cmdlets to convert objects to CSV strings in a file (and back). These cmdlets are the same as the ConvertTo-CSV and ConvertFrom-CSV cmdlets, except that they save the CSV strings in a file.

Parameters

-Delimiter <char>

Specifies the delimiter that separates the property values in the CSV strings. The default is a comma (,). Enter a character, such as a colon (:). To specify a semicolon (;), enclose it in quotation marks.

If you specify a character other than the delimiter used in the CSV strings, ConvertFrom-CSV cannot create objects from the CSV strings. Instead, it returns the strings.

Required? | false
Position? | 2
Default Value | ','
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Header <string[]>

Specifies an alternate column header row for the imported string. The column header determines the names of the properties of the object that ConvertFrom-CSV creates.

Enter a comma-separated list of the column headers. Enclose each item in quotation marks (single or double). Do not enclose the header string in quotation marks. If you enter fewer column headers than there are columns, the remaining columns will have no headers. If you enter more headers than there are columns, the extra headers are ignored.

When using the Header parameter, omit the column header string from the CSV strings. Otherwise, ConvertFrom-CSV creates an extra object from the items in the header row.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <PSObject[]>

Specifies the CSV strings to be converted to objects. Enter a variable that contains the CSV strings or type a command or expression that gets the CSV strings. You can also pipe the CSV strings to ConvertFrom-CSV.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-UseCulture

Use the list separator for the current culture as the string delimiter. The default is a comma (,).

To find the list separator for a culture, use the following command: (Get-Culture).TextInfo.ListSeparator. If you specify a character other than the delimiter used in the CSV strings, ConvertFrom-CSV cannot create objects from the CSV strings. Instead, it returns the strings.

Required? | true
Position? | named
Default Value | Comma
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe CSV strings to ConvertFrom-CSV.
Outputs | System.Management.Automation.PSObject ConvertFrom-CSV returns the objects described by the properties in the CSV strings.

Notes

Because the imported objects are CSV versions of the object type, they are not recognized and formatted by the Windows PowerShell type formatting entries that format the non-CSV versions of the object type.

In CSV format, each object is represented by a comma-separated list of the property values of the object. The property values are converted to strings (by using the ToString() method of the object), so they are generally represented by the name of the property value. ConvertTo-CSV does not export the methods of the object.

Example 1

C:\PS>$p = get-process | convertto-csv

C:\PS> $p | convertfrom-csv

These commands convert the processes on the local computer into CSV format and then restore them to object form.

The first command uses the Get-Process cmdlet to get the processes on the local computer. A pipeline operator (|) sends them to the ConvertTo-CSV cmdlet, which converts the process object to CSV format. The CSV strings are saved in the $p variable.

The second command uses a pipeline operator to send the CSV strings in the $p variable to the ConvertFrom-CSV cmdlet. The cmdlet converts the CSV strings into CSV versions of the original process objects.

Example 2

C:\PS>$date = get-date | convertto-csv -delimiter ";"

C:\PS> convertfrom-csv -inputobject $date -delimiter ";"

These commands convert a data object to CSV format and then to CSV object format.

The first command uses the Get-Date cmdlet to get the current date and time. A pipeline object (|) sends the date to the ConvertTo-CSV cmdlets, which converts the date object to a series of CSV strings. The command uses the Delimiter parameter to specify a semicolon delimiter. The strings are saved in the $date variable.

The second command uses the ConvertFrom-CSV cmdlet to convert the CSV strings in the $date variable back to object format. The command uses the InputObject parameter to specify the CSV strings and the Delimiter parameter to specify the semicolon delimiter.

Example 3

C:\PS>$j = start-job -scriptblock { get-process } | convertto-csv

C:\PS> $header = "MoreData","StatusMessage","Location","Command","State","Finished","InstanceId","SessionId","Name","ChildJobs","Output","Error","Progress","Verbose","Debug","Warning","StateChanged"

# Delete header from $j
C:\PS> $j = $j[0], $j[2..($j.count - 1)]

$j | convertfrom-csv -header $header

MoreData      : True
StatusMessage :
Location      : localhost
Command       : get-process
State         : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : 6fcb6578-7f42-4d93-9f23-9937f6aac1a2
SessionId     : 1
Name          : Job1
ChildJobs     : System.Collections.Generic.List`1[System.Management.Automation.Job]
Output        : System.Management.Automation.PSDataCollection`1[System.Management.Automation.PSObject]
Error         : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ErrorRecord]
Progress      : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ProgressRecord]
Verbose       : System.Management.Automation.PSDataCollection`1[System.String]
Debug         : System.Management.Automation.PSDataCollection`1[System.String]
Warning       : System.Management.Automation.PSDataCollection`1[System.String]
StateChanged  :

Description
-----------
This example shows how to use the Header parameter of ConvertFrom-Csv to change the names of properties in the resulting imported object.

The first command uses the Start-Job cmdlet to start a background job that runs a Get-Process command on the local computer. A pipeline operator (|) sends the resulting job object to the ConvertTo-CSV cmdlet, which converts the job object to CSV format. An assignment operator (=) saves the resulting CSV in the $j variable.

The second command saves a header in the $header variable. Unlike the default header, this header uses "MoreData" instead of "HasMoreData" and "State" instead of "JobStateInfo".

The third command deletes the original header (the second line) from the CSV strings and returns it to the $j variable.

The fourth command uses the ConvertFrom-CSV cmdlet to convert the CSV strings to a CSV version of the job object. The command uses a pipeline operator to send the content in $j to ConvertFrom-CSV. The resulting object has "MoreData" and "State" properties, as specified by the header.

Example 4

C:\PS>(get-culture).textinfo.listseparator

C:\PS> ConvertFrom-Csv -inputobject $services -UseCulture

The command uses the ConvertFrom-CSV cmdlet to convert CSV strings of service objects that had been converted by the ConvertTo-CSV cmdlet. The command uses the UseCulture parameter to direct ConvertFrom-CSV to use the delimiter (list separator) of the current culture.

When using the UseCulture parameter, be sure that the list separator of the current culture matches the delimiter used in the CSV strings. Otherwise, ConvertFrom-CSV cannot generate objects from the CSV strings.

In this example, a Get-Culture command was used to verify the list separator, before the ConvertFrom-CSV command was used.

See Also

  • ConvertTo-CSV
  • Export-CSV
  • Import-CSV


ConvertFrom-SecureString

Converts a secure string into an encrypted standard string.

Syntax

ConvertFrom-SecureString [-Key <Byte[]>] [-SecureString] <SecureString> [<CommonParameters>]

ConvertFrom-SecureString [[-SecureKey] <SecureString>] [-SecureString] <SecureString> [<CommonParameters>]

Description

The ConvertFrom-SecureString cmdlet converts a secure string (System.Security.SecureString) into an encrypted standard string (System.String). Unlike a secure string, an encrypted standard string can be saved in a file for later use. The encrypted standard string can be converted back to its secure string format by using the ConvertTo-SecureString cmdlet. If an encryption key is specified by using the Key or SecureKey parameters, the Rijndael encryption algorithm is used. The specified key must have a length of 128, 192, or 256 bits because those are the key lengths supported by the Rijndael encryption algorithm. If no key is specified, the Windows Data Protection API (DPAPI) is used to encrypt the standard string representation.

Parameters

-Key <Byte[]>

Specifies the encryption key as a byte array.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SecureKey <SecureString>

Specifies the encryption key as a secure string. The secure string value is converted to a byte array before being used as the key.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SecureString <SecureString>

Specifies the secure string to convert to an encrypted standard string.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Security.SecureString You can pipe a SecureString object to ConvertFrom-SecureString.
Outputs | System.String ConvertFrom-SecureString returns a standard string object.

Notes

To create a secure string from characters that are typed at the command prompt, use the AsSecureString parameter of the Read-Host cmdlet.

When you use the Key or SecureKey parameters to specify a key, the key length must be correct. For example, a key of 128 bits can be specified as a byte array of 16 digits. Similarly, 192-bit and 256-bit keys correspond to byte arrays of 24 and 32 digits, respectively.

Example 1

C:\PS>$securestring = read-host -assecurestring

This command creates a secure string from characters that you type at the command prompt. After entering the command, type the string you want to store as a secure string. An asterisk (*) will be displayed to represent each character that you type.

Example 2

C:\PS>$standardstring = convertfrom-securestring  $securestring

This command converts the secure string in the $securestring variable to an encrypted standard string. The resulting encrypted standard string is stored in the $standardstring variable.

Example 3

C:\PS>$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)

C:\PS> $standardstring = convertfrom-securestring  $securestring -key $key

These commands use the Rijndael algorithm to convert the secure string stored in the $securestring variable to an encrypted standard string with a 192-bit key. The resulting encrypted standard string is stored in the $standardstring variable.

The first command stores a key in the $key variable. The key is an array of 24 digits, all of which are less than 256.

Because each digit represents a byte (8 bits), the key has 24 digits for a total of 192 bits (8 x 24). This is a valid key length for the Rijndael algorithm. Each individual value is less than 256, which is the maximum value that can be stored in an unsigned byte.

The second command uses the key in the $key variable to convert the secure string to an encrypted standard string.

See Also

  • ConvertTo-SecureString
  • Read-Host


ConvertFrom-StringData

Converts a string containing one or more key/value pairs to a hash table.

Syntax

ConvertFrom-StringData [-StringData] <string> [<CommonParameters>]

Description

The ConvertFrom-StringData cmdlet converts a string that contains one or more key/value pairs into a hash table. Because each key/value pair must be on a separate line, here-strings are often used as the input format.

The ConvertFrom-StringData cmdlet is considered to be a safe cmdlet that can be used in the DATA section of a script or function. When used in a DATA section, the contents of the string must conform to the rules for a DATA section. For more information, see about_Data_Sections.

Parameters

-StringData <string>

Specifies the string to be converted. You can use this parameter or pipe a string to ConvertFrom-StringData. The parameter name is optional.

The value of this parameter must be a string that is enclosed in single quotation marks (a single-quoted string) or a string that is enclosed in double quotation marks (a double-quoted string) or a here-string containing one or more key/value pairs. Each key/value pair must be on a separate line, or each pair must be separated by newline characters (`n).

You can include comments in the string, but the comments cannot be on the same line as a key/value pair. The comments are not included in the hash table.

A here-string is a string consisting of one or more lines within which quotation marks are interpreted literally. For more information, see about_Quoting_Rules.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string containing a key/value pair to ConvertFrom-StringData.
Outputs | System.Collections.Hashtable ConvertFrom-StringData returns a hash table that it creates from the key/value pairs.

Notes

A here-string is a string consisting of one or more lines within which quotation marks are interpreted literally. For more information, see about_Quoting_Rules.

ConvertFrom-StringData can be useful in scripts that display user messages in multiple spoken languages. You can use the dictionary-style hash tables to isolate text strings from code, such as in resource files, and to format the text strings for use in translation tools.

Example 1

C:\PS>$here = @'
Msg1 = The string parameter is required.
Msg2 = Credentials are required for this command.
Msg3 = The specified variable does not exist.
'@

C:\PS> convertfrom-stringdata -stringdata $here

Name                           Value
----                           -----
Msg3                           The specified variable does not exist.
Msg2                           Credentials are required for this command.
Msg1                           The string parameter is required.

Description
-----------
These commands convert a single-quoted here-string of user messages into a hash table. In a single-quoted string, values are not substituted for variables and expressions are not evaluated.

The first command creates a here-string and saves it in the $here variable.

The second command uses the ConvertFrom-StringData cmdlet to convert the here-string in the $here variable to a hash table.

Example 2

C:\PS>$p = @"
ISE = Windows PowerShell Integrated Scripting Environment
"@

C:\PS> $p | get-member

   TypeName: System.String

Name             MemberType            Definition
----             ----------            ----------
Clone            Method                System.Object Clone()
...

C:\PS> $hash = convertfrom-stringdata -stringdata $p

C:\PS> $hash | get-member

   TypeName: System.Collections.Hashtable

Name              MemberType            Definition
----              ----------            ----------
Add               Method                System.Void Add(Object key, Object
...

Description
-----------
These commands demonstrate that ConvertFrom-StringData actually converts a here-string to a hash table.

The first command creates a double-quoted here-string that includes one key/value" pair and saves it in the $p variable.

The second command uses a pipeline operator (|) to send the $p variable to the Get-Member cmdlet. The result shows that $p is a string (System.String).

The third command uses the ConvertFrom-StringData cmdlet to convert the here-string in $p to a hash table. The command stores the result in the $hash variable.

The final command uses a pipeline operator (|) to send the $hash variable to the Get-Member cmdlet. The result shows that the content of the $hash variable is a hash table (System.Collections.Hashtable).

Example 3

C:\PS>convertfrom-stringdata -stringdata @'
   Name = Disks.ps1
   # Category is optional.
   Category = Storage
   Cost = Free
'@

Name                           Value
----                           -----
Cost                           Free
Category                       Storage
Name                           Disks.ps1

Description
-----------
This command converts a single-quoted here-string that contains multiple key/value pairs into a hash table.

In this command, the value of the StringData parameter is a here-string, instead of a variable that contains a here-string. Either format is valid.

The here-string includes a comment about one of the strings. Comments are valid in strings, provided that the comment is on a different line than a key/value pair.

Example 4

C:\PS>$a = convertfrom-stringdata -stringdata "Top = Red `n Bottom = Blue"

C:\PS> "Top = " + $a.Top
Top = Red

C:\PS> "Bottom = " + $a.Bottom
Bottom = Blue

Description
-----------
This example converts a regular double-quoted string (not a here-string) into a hash table and saves it in the $a variable.

To satisfy the condition that each key/value pair must be on a separate line, it uses the Windows PowerShell newline character (`n) to separate the pairs.

The result is a hash table of the input. The remaining commands display the output.

Example 5

C:\PS>$TextMsgs = DATA {
  ConvertFrom-StringData @'
    Text001 = The $Notebook variable contains the 	name of the user's system notebook.
    Text002 = The $MyNotebook variable contains the 	name of the user's private notebook.
'@
}

C:\PS> $TextMsgs.Text001
The $Notebook variable contains the name of the user's system notebook.

C:\PS> $TextMsgs.Text002
The $MyNotebook variable contains the name of the user's private notebook.

Description
-----------
This example shows a ConvertFrom-StringData command used in the DATA section of a script. The statements below the DATA section display the text to the user.

Because the text includes variable names, it must be enclosed in a single-quoted string so that the variables are interpreted literally and not expanded. Variables are not permitted in the DATA section.

Example 6

C:\PS>$here = @'
Msg1 = The string parameter is required.
Msg2 = Credentials are required for this command.
Msg3 = The specified variable does not exist.
'@

C:\PS> $hash = $here | convertfrom-stringdata

C:\PS> $hash

Name     Value
----     -----
Msg3     The specified variable does not exist.
Msg2     Credentials are required for this command.
Msg1     The string parameter is required.

Description
-----------
This example shows that you can use a pipeline operator (|) to send a string to ConvertFrom-StringData.

The first command saves a here-string in the $here variable. The second command uses a pipeline operator (|) to send the $here variable to ConvertFrom-StringData. The command saves the result in the $hash variable.

The final command displays the contents of the $hash variable.

See Also

  • about_Data_Sections
  • about_Quoting_Rules
  • about_Script_Internationalization


Convert-Path

Converts a path from a Windows PowerShell path to a Windows PowerShell provider path.

Syntax

Convert-Path [-LiteralPath] <string[]> [-UseTransaction] [<CommonParameters>]

Convert-Path [-Path] <string[]> [-UseTransaction] [<CommonParameters>]

Description

The Convert-Path cmdlet converts a path from a Windows PowerShell path to a Windows PowerShell provider path.

Parameters

-LiteralPath <string[]>

Specifies the path to be converted. The value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the Windows PowerShell path to be converted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a path (but not a literal path) to Convert-Path.
Outputs | System.String Convert-Path returns a string that contains the converted path.

Notes

The cmdlets that contain the Path noun (the Path cmdlets) manipulate path names and return the names in a concise format that all Windows PowerShell providers can interpret. They are designed for use in programs and scripts where you want to display all or part of a path name in a particular format. Use them like you would use Dirname, Normpath, Realpath, Join, or other path manipulators.

You can use the path cmdlets with several providers, including the FileSystem, Registry, and Certificate providers.

The Convert-Path cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>convert-path ~

This command expands the current working directory.

Example 2

C:\PS>convert-path HKLM:\software\microsoft

This command converts the Windows PowerShell provider path to a standard registry path.

See Also

  • about_Providers
  • Test-Path
  • Split-Path
  • Resolve-Path
  • Join-Path


ConvertTo-CSV

Converts Microsoft .NET Framework objects into a series of comma-separated value (CSV) variable-length strings.

Syntax

ConvertTo-CSV [[-Delimiter] <char>] [-InputObject] <psobject> [-NoTypeInformation] [<CommonParameters>]

ConvertTo-CSV [-UseCulture] [-InputObject] <psobject> [-NoTypeInformation] [<CommonParameters>]

Description

The ConvertTo-CSV cmdlet returns a series of comma-separated, variable-length (CSV) strings that represents the objects that you submit. You can then use the ConvertFrom-CSV cmdlet to re-create objects from the CSV strings. The resulting objects are CSV versions of the original objects that consist of string representations of the property values and no methods.

You can also use the Export-CSV and Import-CSV cmdlets to convert .NET Framework objects to CSV strings (and back). Export-CSV is the same as ConvertTo-CSV, except that it saves the CSV strings in a file.

You can use the parameters of the ConvertTo-CSV cmdlet to specify a delimiter other than a comma or to direct ConvertTo-CSV to use the default delimiter for the current culture.

For more information, see Export-CSV, and see the Notes section.

Parameters

-Delimiter <char>

Specifies a delimiter to separate the property values. The default is a comma (,). Enter a character, such as a colon (:).

To specify a semicolon (;), enclose it in quotation marks. Otherwise, it will be interpreted as the command delimiter.

Required? | false
Position? | 2
Default Value | , (comma)
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to export as CSV strings. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe objects to ConvertTo-CSV.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-NoTypeInformation

Omits the type information header from the output. By default, the string in the output contains "#TYPE " followed by the fully-qualified name of the type of the .NET Framework object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseCulture

Uses the list separator for the current culture as the data delimiter. The default is a comma (,).

This parameter is very useful in scripts that are being distributed to users worldwide. To find the list separator for a culture, use the following command: (Get-Culture).TextInfo.ListSeparator.

Required? | false
Position? | named
Default Value | Comma
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any .NET Framework object to ConvertTo-CSV.
Outputs | System.String The CSV output is returned as a collection of strings.

Notes

In CSV format, each object is represented by a comma-separated list of its property value. The property values are converted to strings (by using the ToString() method of the object), so they are generally represented by the name of the property value. ConvertTo-CSV does not export the methods of the object.

The format of the resulting CSV strings is as follows:

-- The first string consists of '#TYPE ' followed by the fully-qualified name of the .NET Framework type of the object, such as #TYPE System.Diagnostics.Process. To suppress this string, use the NoTypeInformation parameter.

-- The next string represents the column headers. It contains a comma-separated list of the names of all the properties of the first object.

-- The remaining strings consist of comma-separated lists of the property values of each object.

When you submit multiple objects to ConvertTo-CSV, ConvertTo-CSV orders the strings based on the properties of the first object that you submit. If the remaining objects do not have one of the specified properties, the property value of that object is null, as represented by two consecutive commas. If the remaining objects have additional properties, those property values are ignored.

Example 1

C:\PS>get-process powershell | convertto-csv

#TYPE System.Diagnostics.Process
"__NounName","Name","Handles","VM","WS","PM","NPM","Path","Company","CPU","FileVersion","ProductVersion","Description",
"Product","BasePriority","ExitCode","HasExited","ExitTime","Handle","HandleCount","Id","MachineName","MainWindowHandle"
,"MainWindowTitle","MainModule","MaxWorkingSet","MinWorkingSet","Modules","NonpagedSystemMemorySize","NonpagedSystemMem
orySize64","PagedMemorySize","PagedMemorySize64","PagedSystemMemorySize","PagedSystemMemorySize64","PeakPagedMemorySize
","PeakPagedMemorySize64","PeakWorkingSet","PeakWorkingSet64","PeakVirtualMemorySize","PeakVirtualMemorySize64","Priori
tyBoostEnabled","PriorityClass","PrivateMemorySize","PrivateMemorySize64","PrivilegedProcessorTime","ProcessName","Proc
essorAffinity","Responding","SessionId","StartInfo","StartTime","SynchronizingObject","Threads","TotalProcessorTime","U
serProcessorTime","VirtualMemorySize","VirtualMemorySize64","EnableRaisingEvents","StandardInput","StandardOutput","Sta
ndardError","WorkingSet","WorkingSet64","Site","Container"
"Process","powershell","216","597544960","60399616","63197184","21692","C:\WINDOWS\system32\WindowsPowerShell\v1.0\powe
rshell.exe","Microsoft Corporation","3.4788223","6.1.6587.1 (fbl_srv_powershell(nigels).070711-0102)","6.1.6587.1","Win
dows PowerShell","Microsoft® Windows® Operating System","8",,"False",,"860","216","5132",".","5636936","Windows PowerSh
ell 2.0 (04/17/2008 00:10:40)","System.Diagnostics.ProcessModule (powershell.exe)","1413120","204800","System.Diagnosti
cs.ProcessModuleCollection","21692","21692","63197184","63197184","320080","320080","63868928","63868928","60715008","6
0715008","598642688","598642688","True","Normal","63197184","63197184","00:00:00.2028013","powershell","15","True","1",
"System.Diagnostics.ProcessStartInfo","4/21/2008 3:49:19 PM",,"System.Diagnostics.ProcessThreadCollection","00:00:03.51
00225","00:00:03.3072212","597544960","597544960","False",,,,"60399616","60399616",,

Description
-----------
This command converts a single process object to CSV format. The command uses the Get-Process cmdlet to get the PowerShell process on the local computer. It uses a pipeline operator (|) to send the command to the ConvertTo-CSV cmdlet, which converts it to a series of comma-separated strings.

Example 2

C:\PS>$date = get-date

C:\PS> convertto-csv -inputobject $date -delimiter ";" -notypeinformation

This example converts a date object to CSV format.

The first command uses the Get-Date cmdlet to get the current date. It saves it in the $date variable.

The second command uses the ConvertTo-CSV cmdlet to convert the DateTime object in the $date variable to CSV format. The command uses the InputObject parameter to specify the object to be converted. It uses the Delimiter parameter to specify the delimiter that separates the object properties. It uses the NoTypeInformation parameter to suppress the #TYPE string.

Example 3

C:\PS>get-eventlog -log "windows powershell" | convertto-csv -useculture

This command converts the Windows PowerShell event log on the local computer to a series of CSV strings.

The command uses the Get-EventLog cmdlet to get the events in the Windows PowerShell log. A pipeline operator (|) sends the events to the ConvertTo-CSV cmdlet, which converts the events to CSV format. The command uses the UseCulture parameter, which uses the list separator for the current culture as the delimiter.

See Also

  • Import-CSV
  • Export-CSV
  • ConvertFrom-CSV


ConvertTo-Html

Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser.

Syntax

ConvertTo-Html [[-Head] <string[]>] [[-Title] <string>] [[-Body] <string[]>] [-CssUri <Uri>] [[-Property] <Object[]>] [-As <string>] [-InputObject <psobject>] [-PostContent <string[]>] [-PreContent <string[]>] [<CommonParameters>]

ConvertTo-Html [-Fragment] [[-Property] <Object[]>] [-As <string>] [-InputObject <psobject>] [-PostContent <string[]>] [-PreContent <string[]>] [<CommonParameters>]

Description

The ConvertTo-Html cmdlet converts .NET Framework objects into HTML that can be displayed in a Web browser. You can use this cmdlet to display the output of a command in a Web page.

You can use the parameters of ConvertTo-Html to select object properties, to specify a table or list format, to specify the HTML page title, to add text before and after the object, and to return only the table or list fragment, instead of a strict DTD page.

When you submit multiple objects to ConvertTo-Html, Windows PowerShell creates the table (or list) based on the properties of the first object that you submit. If the remaining objects do not have one of the specified properties, the property value of that object is an empty cell. If the remaining objects have additional properties, those property values are not included in the file.

Parameters

-As <string>

Determines whether the object is formatted as a table or a list. Valid values are TABLE and LIST. The default value is TABLE.

The TABLE value generates an HTML table that resembles the Windows PowerShell table format. The header row displays the property names. Each table row represents an object and displays the object's values for each property.

The LIST value generates a two-column HTML table for each object that resembles the Windows PowerShell list format. The first column displays the property name; the second column displays the property value.

Required? | false
Position? | named
Default Value | Table
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Body <string[]>

Specifies the text to add after the opening <BODY> tag. By default, there is no text in that position.

Required? | false
Position? | 4
Default Value | No text.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CssUri <Uri>

Specifies the Uniform Resource Identifier (URI) of the cascading style sheet (CSS) that is applied to the HTML file. The URI is included in a style sheet link in the output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Fragment

Generates only an HTML table. The HTML, HEAD, TITLE, and BODY tags are omitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Head <string[]>

Specifies the content of the <HEAD> tag. The default is "<title>HTML TABLE</title>". If you use the Head parameter, the Title parameter is ignored.

Required? | false
Position? | 2
Default Value | <title>HTML TABLE</title>
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be represented in HTML. Enter a variable that contains the objects or type a command or expression that gets the objects.

If you use this parameter to submit multiple objects, such as all of the services on a computer, ConvertTo-Html creates a table that displays the properties of a collection or of an array of objects (System.Object[]). To create a table of the individual objects, use the pipeline operator to pipe the objects to ConvertTo-Html.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-PostContent <string[]>

Specifies text to add after the closing </TABLE> tag. By default, there is no text in that position.

Required? | false
Position? | named
Default Value | No text
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PreContent <string[]>

Specifies text to add before the opening <TABLE> tag. By default, there is no text in that position.

Required? | false
Position? | named
Default Value | No text
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Property <Object[]>

Includes the specified properties of the objects in the HTML.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Title <string>

Specifies a title for the HTML file, that is, the text that appears between the <TITLE> tags.

Required? | false
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any .NET object to ConvertTo-Html.
Outputs | System.String ConvertTo-Html returns series of strings that comprise valid HTML.

Notes

To use this cmdlet, pipe one or more objects to the cmdlet or use the InputObject parameter to specify the object. When the input consists of multiple objects, the output of these two methods is quite different.

-- When you pipe multiple objects to a cmdlet, Windows PowerShell sends the objects to the cmdlet one at a time. As a result, ConvertTo-Html creates a table that displays the individual objects. For example, if you pipe the processes on a computer to ConvertTo-Html, the resulting table displays all of the processes.

-- When you use the InputObject parameter to submit multiple objects, ConvertTo-Html receives these objects as a collection or as an array. As a result, it creates a table that displays the array and its properties, not the items in the array. For example, if you use InputObject to submit the processes on a computer to ConvertTo-Html, the resulting table displays an object array (System.Object[]) and its properties.

To comply with the XHTML Strict DTD,the DOCTYPE tag is modified accordingly:

(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">)

Example 1

C:\PS>convertto-html -inputobject (get-date)

This command creates an HTML page that displays the properties of the current date. It uses the InputObject parameter to submit the results of a Get-Date command to the ConvertTo-Html cmdlet.

Example 2

C:\PS>get-alias | convertto-html > aliases.htm

C:\PS> invoke-item aliases.htm

This command creates an HTML page that lists the Windows PowerShell aliases in the current console.

The command uses the Get-Alias cmdlet to get the aliases. It uses the pipeline operator (|) to send the aliases to the ConvertTo-Html cmdlet, which creates the HTML page.

Example 3

C:\PS>get-eventlog -logname "Windows PowerShell | convertto-html > pslog.htm

This command creates an HTML page called pslog.htm that displays the events in the Windows PowerShell event log on the local computer.

It uses the Get-EventLog cmdlet to get the events in the Windows PowerShell log and then uses the pipeline operator (|) to send the events to the ConvertTo-Html cmdlet.

The command also uses the redirection operator (>) to send the HTML code to the pslog.htm file.

Example 4

C:\PS>get-process | convertto-html -property Name, Path, Company -title "Process Information" > proc.htm; ii proc.htm

These commands create and open an HTML page that lists the name, path, and company of the processes on the local computer.

The first command uses the Get-Process cmdlet to get objects that represent the processes running on the computer. The command uses the pipeline operator (|) to send the process objects to the ConvertTo-Html cmdlet.

The command uses the Property parameter to select three properties of the process objects to be included in the table. The command uses the Title parameter to specify a title for the HTML page. The command also uses the redirection operator (>) to send the resulting HTML to a file named Proc.htm.

The second command uses the Invoke-Item cmdlet (alias = ii) to open the Proc.htm in the default browser. The two commands are separated by a semicolon (;).

Example 5

C:\PS>get-service | convertto-html -CssUri "test.css"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>HTML TABLE</title>
<link rel="stylesheet" type="text/css" href="test.css" />
...

Description
-----------
This command creates an HTML page of the service objects that the Get-Service cmdlet returns. The command uses the CssUri parameter to specify a cascading style sheet for the HTML page.

The CssUri parameter adds an additional "<link rel="stylesheet" type="text/css" tag to the resulting HTML. The HREF attribute in the tag contains the name of the style sheet.

Example 6

C:\PS>get-service | convertto-html -as LIST > services.htm

This command creates an HTML page of the service objects that the Get-Service cmdlet returns. The command uses the As parameter to specify a list format. The redirection operator (>) sends the resulting HTML to the Services.htm file.

Example 7

C:\PS>get-date | cth -fragment

<table>
<colgroup>...</colgroup>
<tr><th>DisplayHint</th><th>DateTime</th><th>Date</th><th>Day</th><th>DayOfWeek</th><th>DayOfYear</th><th>Hour</th><th>
Kind</th><th>Millisecond</th><th>Minute</th><th>Month</th><th>Second</th><th>Ticks</th><th>TimeOfDay</th><th>Year</th><
/tr>
<tr><td>DateTime</td><td>Monday, May 05, 2008 10:40:04 AM</td><td>5/5/2008 12:00:00 AM</td><td>5</td><td>Monday</td><td
>126</td><td>10</td><td>Local</td><td>123</td><td>40</td><td>5</td><td>4</td><td>633455808041237213</td><td>10:40:04.12
37213</td><td>2008</td></tr>
</table>

Description
-----------
This command uses ConvertTo-Html to generate an HTML table of the current date. The command uses the Get-Date cmdlet to get the current date. It uses a pipeline operator (|) to send the results to the ConvertTo-Html cmdlet (aliased as "cth").

The ConvertTo-Html command includes the Fragment parameter, which limits the output to an HTML table. As a result, the other elements of an HTML page, such as the <HEAD> and <BODY> tags, are omitted.

Example 8

C:\PS>get-eventlog -log "Windows PowerShell" | convertto-html -property id, level, task

This command uses the Get-EventLog cmdlet to get events from the "Windows PowerShell" event log.

It uses a pipeline operator (|) to send the events to the ConvertTo-Html cmdlet, which converts the events to HTML format.

The ConvertTo-Html command uses the Property parameter to select only the ID, Level, and Task properties of the event.

Example 9

C:\PS>get-service A* | ConvertTo-Html -title "Windows Services: Server01" -body (get-date) -pre "<P>Generated by Corporate IT</P
>" -post "For details, contact Corporate IT." > services.htm; ii services.htm

This command creates and opens a Web page that displays the services on the computer that begin with "A". It uses the Title, Body, PreContent, and PostContent parameters of ConvertTo-Html to customize the output.

The first part of the command uses the Get-Service cmdlet to get the services on the computer that begin with "A". The command uses a pipeline operator (|) to send the results to the ConvertTo-Html cmdlet. The command uses a redirection operator (>) to send the output to the Services.htm file.

A semicolon (;) ends the first command and starts a second command, which uses the Invoke-Item cmdlet (alias = "ii") to open the Services.htm file in the default browser.

See Also

  • ConvertTo-CSV
  • ConvertTo-XML


ConvertTo-SecureString

Converts encrypted standard strings to secure strings. It can also convert plain text to secure strings. It is used with ConvertFrom-SecureString and Read-Host.

Syntax

ConvertTo-SecureString [-Key <Byte[]>] [-String] <string> [<CommonParameters>]

ConvertTo-SecureString [-AsPlainText] [-Force] [-String] <string> [<CommonParameters>]

ConvertTo-SecureString [[-SecureKey] <SecureString>] [-String] <string> [<CommonParameters>]

Description

The ConvertTo-SecureString cmdlet converts encrypted standard strings into secure strings. It can also convert plain text to secure strings. It is used with ConvertFrom-SecureString and Read-Host. The secure string created by the cmdlet can be used with cmdlets or functions that require a parameter of type SecureString. The secure string can be converted back to an encrypted, standard string using the ConvertFrom-SecureString cmdlet. This enables it to be stored in a file for later use.

If the standard string being converted was encrypted with ConvertFrom-SecureString using a specified key, that same key must be provided as the value of the Key or SecureKey parameter of the ConvertTo-SecureString cmdlet.

Parameters

-AsPlainText

Specifies a plain text string to convert to a secure string. The secure string cmdlets help protect confidential text. The text is encrypted for privacy and is deleted from computer memory after it is used. If you use this parameter to provide plain text as input, the system cannot protect that input in this manner. To use this parameter, you must also specify the Force parameter.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Confirms that you understand the implications of using the AsPlainText parameter and still want to use it.

Required? | false
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Key <Byte[]>

Specifies the encryption key to use when converting a secure string into an encrypted standard string. Valid key lengths are 16, 24, and 32 bytes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SecureKey <SecureString>

Specifies the encryption key to use when converting a secure string into an encrypted standard string. The key must be provided in the format of a secure string. The secure string is converted to a byte array before being used as the key. Valid key lengths are 16, 24, and 32 bytes.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-String <string>

Specifies the string to convert to a secure string.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a standard encrypted string to ConvertTo-SecureString.
Outputs | System.Security.SecureString ConvertTo-SecureString returns a SecureString object.

Example 1

C:\PS>$secure = read-host -assecurestring

C:\PS> $secure
System.Security.SecureString

C:\PS> $encrypted = convertfrom-securestring -securestring $secure
C:\PS> $encrypted
01000000d08c9ddf0115d1118c7a00c04fc297eb010000001a114d45b8dd3f4aa11ad7c0abdae9800000000002000000000003660000a8000000100000005df63cea84bfb7d70bd6842e7
efa79820000000004800000a000000010000000f10cd0f4a99a8d5814d94e0687d7430b100000008bf11f1960158405b2779613e9352c6d14000000e6b7bf46a9d485ff211b9b2a2df3bd
6eb67aae41

C:\PS> $secure2 = convertto-securestring -string $encrypted
C:\PS> $secure2
System.Security.SecureString

Description
-----------
This example shows how to create a secure string from user input, convert the secure string to an encrypted standard string, and then convert the encrypted standard string back to a secure string.

The first command uses the AsSecureString parameter of the Read-Host cmdlet to create a secure string. After you enter the command, any characters that you type are converted into a secure string and then saved in the $secure variable.

The second command displays the contents of the $secure variable. Because the $secure variable contains a secure string, Windows PowerShell displays only the System.Security.SecureString type.

The third command uses the ConvertFrom-SecureString cmdlet to convert the secure string in the $secure variable into an encrypted standard string. It saves the result in the $encrypted variable. The fourth command displays the encrypted string in the value of the $encrypted variable.

The fifth command uses the ConvertTo-SecureString cmdlet to convert the encrypted standard string in the $encrypted variable back into a secure string. It saves the result in the $secure2 variable. The sixth command displays the value of the $secure2 variable. The SecureString type indicates that the command was successful.

Example 2

C:\PS>$secure = read-host -assecurestring

C:\PS> $encrypted = convertfrom-securestring -secureString $secure -key (1..16)

C:\PS> $encrypted | set-content encrypted.txt

C:\PS> $secure2 = get-content encrypted.txt | convertto-securestring -key (1..16)

Description
-----------
This example shows how to create a secure string from an encrypted standard string that is saved in a file.

The first command uses the AsSecureString parameter of the Read-Host cmdlet to create a secure string. After you enter the command, any characters that you type are converted into a secure string and then saved in the $secure variable.

The second command uses the ConvertFrom-SecureString cmdlet to convert the secure string in the $secure variable into an encrypted standard string by using the specified key. The contents are saved in the $encrypted variable.

The third command uses a pipeline operator (|) to send the value of the $encrypted variable to the Set-Content cmdlet, which saves the value in the Encrypted.txt file.

The fourth command uses the Get-Content cmdlet to get the encrypted standard string in the Encrypted.txt file. The command uses a pipeline operator to send the encrypted string to the ConvertTo-SecureString cmdlet, which converts it to a secure string by using the specified key. The results are saved in the $secure2 variable.

Example 3

C:\PS>$secure_string_pwd = convertto-securestring "P@ssW0rD!" -asplaintext -force

This command converts the plain text string "P@ssW0rD!" into a secure string and stores the result in the $secure_string_pwd variable. To use the AsPlainText parameter, the Force parameter must also be included in the command.

See Also

  • ConvertFrom-SecureString
  • Read-Host


ConvertTo-XML

Creates an XML-based representation of an object.

Syntax

ConvertTo-XML [-InputObject] <psobject> [-As <string>] [-Depth <int>] [-NoTypeInformation] [<CommonParameters>]

Description

The ConvertTo-Xml cmdlet creates an XML-based representation of one or more Microsoft .NET Framework objects. To use this cmdlet, pipe one or more objects to the cmdlet, or use the InputObject parameter to specify the object.

When you pipe multiple objects to ConvertTo-XML or use the InputObject parameter to submit multiple objects, ConvertTo-XML returns a single XML document that includes representations of all of the objects.

This cmdlet is similar to Export-Clixml except that Export-Clixml stores the resulting XML in a file. ConvertTo-XML returns the XML, so you can continue to process it in Windows PowerShell.

Parameters

-As <string>

Determines the output format. Valid values are:

-- String: Returns a single string.

-- Stream: Returns an array of strings.

-- Document: Returns an XmlDocument object.

Stream is the default.

Required? | false
Position? | named
Default Value | Stream
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Depth <int>

Specifies how many levels of contained objects are included in the XML representation. The default value is 1.

For example, if the object's properties also contain objects, to save an XML representation of the properties of the contained objects, you must specify a depth of 2.

The default value can be overridden for the object type in the Types.ps1xml files. For more information, see about_Types.ps1xml.

Required? | false
Position? | named
Default Value | 1
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the object to be converted. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe objects to ConvertTo-XML.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | true

-NoTypeInformation

Omits the Type attribute from the object nodes.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to ConvertTo-XML.
Outputs | System.String or System.Xml.XmlDocument The value of the As parameter determines the type of object that ConvertTo-XML returns.

Example 1

C:\PS>get-date | convertto-xml

This command converts the current date (a DateTime object) to XML.

Example 2

C:\PS>convertto-xml -as Document -inputObject (get-process) -depth 3

This command converts the process objects that represent all of the processes on the computer into an XML document. The objects are expanded to a depth of three levels.

See Also

  • Export-Clixml
  • Import-Clixml
  • ConvertTo-Html
  • ConvertTo-CSV


Copy-Item

Copies an item from one location to another within a namespace.

Syntax

Copy-Item [-LiteralPath] <string[]> [[-Destination] <string>] [-Container] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Recurse] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Copy-Item [-Path] <string[]> [[-Destination] <string>] [-Container] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Recurse] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Copy-Item cmdlet copies an item from one location to another in a namespace. Copy-Item does not delete the items being copied. The particular items that the cmdlet can copy depend on the Windows PowerShell providers available. For example, when used with the FileSystem Provider, it can copy files and directories and when used with the Registry Provider, it can copy registry keys and entries.

Parameters

-Container

Preserves container objects during the copy operation.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Destination <string>

Specifies the path to the location where the items are to be copied.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to copy items that cannot otherwise be changed, such as copying over a read-only file or alias.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Specifies only those items upon which the cmdlet will act, excluding all others.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the item. The value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing each copied item. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the items to copy.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Recurse

Specifies a recursive copy.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Copy-ItemProperty.
Outputs | None or an object representing the copied item. When you use the PassThru parameter, Copy-Item returns an object that represents the copied item. Otherwise, this cmdlet does not generate any output.

Notes

Copy-Item is like the 'cp' or 'copy' commands in other shells.

The Copy-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>copy-item C:\Wabash\Logfiles\mar1604.log.txt -destination C:\Presentation

This command will copy the file mar1604.log.txt to the C:\Presentation directory. The command does not delete the original file.

Example 2

C:\PS>copy-item C:\Logfiles -destination C:\Drawings -recurse

This command copies the entire contents of the Logfiles directory into the Drawings directory. If the source directory contains files in subdirectories, those subdirectories will be copied with their file trees intact. The Container parameter is set to true by default. This preserves the directory structure.

Example 3

C:\PS>copy-item C:\Logfiles -destination C:\Drawings\Logs -recurse

This command copies the contents of the C:\Logfiles directory to the C:\Drawings\Logs directory. It will create the subdirectory \Logs if it does not already exist.

See Also

  • about_Providers
  • Clear-Item
  • Get-Item
  • Invoke-Item
  • Move-Item
  • Set-Item
  • New-Item
  • Remove-Item
  • Rename-Item


Copy-ItemProperty

Copies a property and value from a specified location to another location.

Syntax

Copy-ItemProperty [-LiteralPath] <string[]> [-Destination] <string> [-Name] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Copy-ItemProperty [-Path] <string[]> [-Destination] <string> [-Name] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Copy-ItemProperty cmdlet copies a property and value from a specified location to another location. For example, you can use Copy-ItemProperty to copy one or more registry entries from one registry key to another registry key.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Destination <string>

Specifies the path to the destination location.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to override restrictions such as renaming existing files as long as security is not compromised.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Specifies only those items upon which the cmdlet will act, excluding all others.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string>

Specifies the name of the property to be copied.

Required? | true
Position? | 3
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the copied item property. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the property to be copied.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Copy-ItemProperty.
Outputs | None or System.Management.Automation.PSCustomObject When you use the Passthru parameter, Copy-ItemProperty generates a PsCustomObject representing the copied item property. Otherwise, this cmdlet does not generate any output.

Notes

The Copy-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>copy-itemproperty -path MyApplication -destination HKLM:\Software\MyApplicationRev2 -name MyProperty

This command copies the property named MyProperty from the MyApplication registry key to the MyApplicationRev2 registry key.

See Also

  • about_Providers
  • Clear-ItemProperty
  • New-ItemProperty
  • Move-ItemProperty
  • Rename-ItemProperty
  • Get-ItemProperty
  • Set-ItemProperty


Debug-Process

Debugs one or more processes running on the local computer.

Syntax

Debug-Process [-Name] <string[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Debug-Process [-Id] <Int32[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Debug-Process -InputObject <Process[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Debug-Process cmdlet attaches a debugger to one or more running processes on a local computer. You can specify the processes by their process name or process ID (PID), or you can pipe process objects to Debug-Process.

Debug-Process attaches the debugger that is currently registered for the process. Before using this cmdlet, verify that a debugger is downloaded and correctly configured.

Parameters

-Id <Int32[]>

Specifies the process IDs of the processes to be debugged. The parameter name ("-Id") is optional.

To find the process ID of a process, type "Get-Process".

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InputObject <Process[]>

Specifies the process objects that represent processes to be debugged. Enter a variable that contains the process objects or a command that gets the process objects, such as a Get-Process command. You can also pipe process objects to Debug-Process.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of the processes to be debugged. If there is more than one process with the same name, Debug-Process attaches a debugger to all processes with that name. The parameter name ("Name") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Int32, System.Diagnostics.Process, System.String You can pipe a process ID (Int32), a process object (System.Diagnostics.Process), or a process name (String) to Debug-Process.
Outputs | None This cmdlet does not generate any output.

Notes

This cmdlet uses the AttachDebugger method of the Windows Management Instrumentation (WMI) Win32_Process class. For more information about this method, see "AttachDebugger Method" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143640.

Example 1

C:\PS>debug-process -name powershell

This command attaches a debugger to the PowerShell process on the computer.

Example 2

C:\PS>debug-process -name sql*

This command attaches a debugger to all processes that have names that begin with "sql".

Example 3

C:\PS>debug-process winlogon, explorer, outlook

This command attaches a debugger to the Winlogon, Explorer, and Outlook processes.

Example 4

C:\PS>debug-process -id 1132, 2028

This command attaches a debugger to the processes that have process IDs 1132 and 2028.

Example 5

C:\PS>get-process powershell | debug-process

This command attaches a debugger to the PowerShell processes on the computer. It uses the Get-Process cmdlet to get the PowerShell processes on the computer, and it uses a pipeline operator (|) to send the processes to the Debug-Process cmdlet.

To specify a particular PowerShell process, use the ID parameter of Get-Process.

Example 6

C:\PS>$pid | debug-process

This command attaches a debugger to the current PowerShell processes on the computer.

It uses the $pid automatic variable, which contains the process ID of the current PowerShell process. Then, it uses a pipeline operator (|) to send the process ID to the Debug-Process cmdlet.

For more information about the $pid automatic variable, see about_Automatic_Variables.

Example 7

C:\PS>get-process -computername Server01, Server02 -name MyApp | debug-process

This command attaches a debugger to the MyApp processes on the Server01 and Server02 computers.

It uses the Get-Process cmdlet to get the MyApp processes on the Server01 and Server02 computers. It uses a pipeline operator to send the processes to the Debug-Process cmdlet, which attaches the debuggers.

Example 8

C:\PS>$p = get-process powershell

C:\PS> debug-process -inputobject $p

This command attaches a debugger to the PowerShell processes on the local computer.

The first command uses the Get-Process cmdlet to get the PowerShell processes on the computer. It saves the resulting process object in the $p variable.

The second command uses the InputObject parameter of Debug-Process to submit the process object in the $p variable to Debug-Process.

See Also

  • Get-Process
  • Start-Process
  • Stop-Process
  • Wait-Process
  • Debug-Process


Disable-ComputerRestore

Disables the System Restore feature on the specified file system drive.

Syntax

Disable-ComputerRestore [-Drive] <string[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Disable-ComputerRestore cmdlet turns off the System Restore feature on one or more file system drives. As a result, attempts to restore the computer do not affect the specified drive.

To disable System Restore on any drive, it must be disabled on the system drive, either first or concurrently.

To re-enable System Restore, use the Enable-ComputerRestore cmdlet. To find the state of System Restore for each drive, use Rstrui.exe.

Parameters

-Drive <string[]>

Specifies the file system drives. Enter one or more file system drive letters, each followed by a colon and a backslash and enclosed in quotation marks, such as "C:\" or "D:\". This parameter is required.

You cannot use this cmdlet to disable System Restore on a remote network drive, even if the drive is mapped to the local computer, and you cannot disable System Restore on drives that are not eligible for System Restore, such as external drives.

To disable System Restore on any drive, System Restore must be disabled on the system drive, either before or concurrently.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not generate any output.

Notes

Disable-ComputerRestore and Enable-ComputerRestore work only on client operating systems, such as Windows Vista and Windows XP.

To run a Disable-ComputerRestore command on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administrator" option.

To find the file system drives that are eligible for system restore, in System in Control Panel, see the System Protection tab. To open this tab in Windows PowerShell, type "SystemPropertiesProtection".

This cmdlet uses the Windows Management Instrumentation (WMI) SystemRestore class.

Example 1

C:\PS>disable-computerrestore -drive "C:\"

This command disables System Restore on the C: drive.

Example 2

C:\PS>disable-computerrestore "C:\", "D:\"

This command disables System Restore on the C: and D: drives. The command uses the Drive parameter, but it the omits the optional parameter name.

See Also

  • Enable-ComputerRestore
  • Get-ComputerRestorePoint
  • Restore-Computer
  • Restart-Computer


Disable-PSBreakpoint

Disables the breakpoints in the current console.

Syntax

Disable-PSBreakpoint [-Id] <Int32[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Disable-PSBreakpoint [-Breakpoint] <Breakpoint[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Disable-PSBreakpoint cmdlet disables breakpoints, which assures that they are not hit when the script runs. You can use it to disable all breakpoints, or you can specify breakpoints by submitting breakpoint objects or breakpoint IDs.

Technically, this cmdlet changes the value of the Enabled property of a breakpoint object to False. To re-enable a breakpoint, use the Enable-PSBreakpoint cmdlet. Breakpoints are enabled by default when you create them by using the Set-PSBreakpoint cmdlet.

A breakpoint is a point in a script where execution stops temporarily so that you can examine the instructions in the script. Disable-PSBreakpoint is one of several cmdlets designed for debugging Windows PowerShell scripts. For more information about the Windows PowerShell debugger, see about_Debuggers.

Parameters

-Breakpoint <Breakpoint[]>

Specifies the breakpoints to disable. Enter a variable that contains breakpoint objects or a command that gets breakpoint objects, such as a Get-PSBreakpoint command. You can also pipe breakpoint objects to the Disable-PSBreakpoint cmdlet.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Id <Int32[]>

Disables the breakpoints with the specified breakpoint IDs. Enter the IDs or a variable that contains the IDs. You cannot pipe IDs to Disable-PSBreakpoint.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the enabled breakpoints. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.Breakpoint You can pipe a breakpoint object to Disable-PSBreakpoint.
Outputs | None or System.Management.Automation.Breakpoint When you use the PassThru parameter, Disable-PSBreakpoint returns an object that represents the disabled breakpoint. Otherwise, this cmdlet does not generate any output.

Example 1

C:\PS>$b = set-psbreakpoint -script sample.ps1 -variable name

C:\PS> $b | disable-psbreakpoint

These commands disable a newly-created breakpoint.

The first command uses the Set-PSBreakpoint cmdlet to create a breakpoint on the Name variable in the Sample.ps1 script. Then, it saves the breakpoint object in the $b variable.

The second command uses the Disable-PSBreakpoint cmdlet to disable the new breakpoint. It uses a pipeline operator (|) to send the breakpoint object in $b to the Disable-PSBreakpoint cmdlet.

As a result of this command, the value of the Enabled property of the breakpoint object in $b is False.

Example 2

C:\PS>disable-psbreakpoint -id 0

This command disables the breakpoint with breakpoint ID 0.

Example 3

C:\PS>disable-psbreakpoint -breakpoint ($b = set-psbreakpoint -script sample.ps1 -line 5)

C:\PS> $b

This command creates a new breakpoint that is disabled until you enable it.

It uses the Disable-PSBreakpoint cmdlet to disable the breakpoint. The value of the Breakpoint parameter is a Set-PSBreakpoint command that sets a new breakpoint, generates a breakpoint object, and saves the object in the $b variable.

Cmdlet parameters that take objects as their values can accept a variable that contains the object or a command that gets or generates the object. In this case, because Set-PSBreakpoint generates a breakpoint object, it can be used as the value of the Breakpoint parameter.

The second command displays the breakpoint object in the value of the $b variable.

Example 4

C:\PS>get-psbreakpoint | disable-psbreakpoint

This command disables all breakpoints in the current console. You can abbreviate this command as: "gbp | dbp".

See Also

  • about_Debuggers
  • Set-PSBreakpoint
  • Get-PSBreakpoint
  • Enable-PSBreakpoint
  • Remove-PSBreakpoint
  • Get-PSCallStack


Disable-PSRemoting

Prevents the computer from receiving remote Windows PowerShell commands.

Syntax

Disable-PSRemoting [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Disable-PSRemoting function disables all session configurations on the local computer by adding a "deny all" entry to their security descriptors. This prevents the local computer from receiving remote commands.

Disable-PSRemoting does not stop the WinRM service and it does not prevent users of the local computer from establishing sessions that connect to remote computers or sending commands to other computers.

To re-enable the session configurations, use the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlets.

To run this function on Windows Vista, Windows Server 2008, and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option.

Parameters

-Force

Suppresses all user prompts. By default, you are prompted to confirm each operation.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not return any object.

Notes

A session configuration is a group of settings that define the environment for a session. The session configurations are located on the remote computer and are used by local and remote sessions that connect to the computer.

Every session that connects to the computer must use one of the session configurations that are registered on the computer. This includes persistent sessions that you create by using New-PSSession or Enter-PSSession cmdlets, and the temporary sessions that Windows PowerShell creates when you use the ComputerName parameter of a cmdlet that uses WS-Management remoting technology, such as Invoke-Command. By denying access to all session configurations, you effectively prevent all users from establishing sessions that connect to the computer.

Disable-PSRemoting is the equivalent of "Disable-PSSessionConfiguration -name *.

Example 1

C:\PS>disable-psremoting

This command disables all session configurations on the computer.

Example 2

C:\PS>disable-psremoting -force

This command disables all session configurations on the computer without prompting.

Example 3

C:\PS>disable-psremoting -force

C:\PS> new-pssession -computername localhost

[localhost] Connecting to remote server failed with the following error
message : Access is denied. For more information, see the about_Remote_Troub
leshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionOpenFailed

C:\PS> new-pssession -computername Server01

 Id Name       ComputerName    State    Configuration         Availability
 -- ----       ------------    -----    -------------         ------------
  1 Session1   Server01...     Opened   Microsoft.PowerShell     Available

C:\PS> enable-pssessionConfiguration -name * -force

C:\PS> new-pssession -computername localhost

 Id Name       ComputerName    State    Configuration         Availability
 -- ----       ------------    -----    -------------         ------------
  1 Session1   localhost       Opened   Microsoft.PowerShell     Available

Description
-----------
This example shows the effect of using Disable-PSRemoting.

The first command uses Disable-PSRemoting to disable all registered session configurations on the local computer.

The second command uses the New-PSSession to create a remote session to the local computer (also known as a "loopback"). Because the session configurations that session requires are disabled, the command fails.

The third command uses the New-PSSession cmdlet to create a session from the local computer to the Server01 remote computer. This command, which uses the session configurations on the remote computer, succeeds.

The fourth command uses the Enable-PSSessionConfiguration cmdlet to re-enable all of the session configurations on the local computer. The command uses a value of * (all) in the Name parameter.

The fifth command attempts again to establish a loopback session by using the New-PSSession cmdlet. This time the command succeeds, because the session configuration that requires are enabled.

Example 4

C:\PS>disable-psremoting -force

C:\PS> get-psSessionConfiguration | format-table -property name, permission -auto

Name                   Permission
----                   ----------
microsoft.powershell   Everyone AccessDenied, BUILTIN\Administrators AccessAllowed
microsoft.powershell32 Everyone AccessDenied, BUILTIN\Administrators AccessAllowed

C:\PS> enable-psremoting -force
WinRM already is set up to receive requests on this machine.
WinRM already is set up for remote management on this machine.

C:\PS>> Get-PSSessionConfiguration | ft name, Permission -auto

Name                   Permission
----                   ----------
microsoft.powershell   BUILTIN\Administrators AccessAllowed
microsoft.powershell32 BUILTIN\Administrators AccessAllowed

Description
-----------
This example shows the effect on the session configurations of using Disable-PSRemoting and Enable-PSRemoting.

The first command uses the Disable-PSRemoting function to disable all registered session configurations. The force parameter suppresses all user prompts.

The second command uses the Get-PSSessionConfiguration cmdlet to display the registered session configurations on the computer. The command uses a pipeline operator to send the results to a Format-Table command, which displays only the Name and Permission properties of the configurations in a table.

The resulting table shows that everyone is denied permission to the configurations.

The third command uses the Enable-PSRemoting cmdlet to re-enable all of the session configurations on the computer. You can also use an "Enable-PsSessionConfiguration -name *" command. The command uses the Force parameter to suppress all user prompts and to restart the WinRM service without prompting.

The fourth command uses Get-PSSessionConfiguration and Format-Table to display the names and permissions of the session configurations. The results show that members of the Administrators group now have access to the session configurations.

See Also

  • Enable-PSRemoting
  • Disable-PSSessionConfiguration
  • Get-PSSessionConfiguration
  • Register-PSSessionConfiguration
  • Set-PSSessionConfiguration
  • Unregister-PSSessionConfiguration
  • WS-Management Provider


Disable-PSSessionConfiguration

Denies access to the session configurations on the local computer.

Syntax

Disable-PSSessionConfiguration [[-Name] <string[]>] [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Disable-PSSessionConfiguration cmdlet prevents all users of the computer from using the session configuration in a session. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users.

The Disable-PSSessionConfiguration cmdlet adds a "deny all" setting to the security descriptor of one or more registered session configurations. As a result, you can unregister, view, and change the configurations, but you cannot use them in a session.

Without parameters, Disable-PSSessionConfiguration disables the Microsoft.PowerShell configuration, which is the default configuration that is used for sessions. Unless the user specifies a different configuration, both local and remote users are effectively prevented from creating any sessions that connect to the computer.

To disable all session configurations on the computer, use Disable-PSRemoting.

Parameters

-Force

Suppresses all user prompts. By default, you are prompted to confirm each operation.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of session configurations to disable. Enter one or more configuration names. Wildcards are permitted. You can also pipe a string that contains a configuration name or a session configuration object to Disable-PSSessionConfiguration.

If you omit this parameter, Disable-PSSessionConfiguration disables the Microsoft.PowerShell session configuration.

Required? | false
Position? | 1
Default Value | Microsoft.PowerShell
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | true

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration, System.String You can pipe a session configuration object or a string that contains the name of a session configuration to Disable-PSSessionConfiguration.
Outputs | None This cmdlet does not return any objects.

Notes

To run this cmdlet on Windows Vista, Windows Server 2008, and later versions of Windows, you must start Windows PowerShell with the "Run as administrator" option.

Example 1

C:\PS>Disable-PSSessionConfiguration

This command disables the Microsoft.PowerShell session configuration.

Example 2

C:\PS>disable-pssessionConfiguration -name *

This command disables all registered session configurations on the computer.

Example 3

C:\PS>disable-pssessionConfiguration -name Microsoft* -force

This command disables all session configurations that have names that begin with "Microsoft". The command uses the Force parameter to suppress all user prompts from the command.

Example 4

C:\PS>Get-PSSessionConfiguration -name MaintenanceShell, AdminShell | Disable-PSSessionConfiguration

This command disables the MaintenanceShell and AdminShell session configurations.

The command uses a pipeline operator (|) to send the results of a Get-PSSessionConfiguration command to Disable-PSSessionConfiguration.

Example 5

C:\PS>Get-PSSessionConfiguration | format-table -property Name, Permission -auto

Name                   Permission
----                   ----------
MaintenanceShell       BUILTIN\Administrators AccessAllowed
microsoft.powershell   BUILTIN\Administrators AccessAllowed
microsoft.powershell32 BUILTIN\Administrators AccessAllowed

C:\PS> Disable-PSSessionConfiguration -name MaintenanceShell -force

C:\PS> Get-PSSessionConfiguration | format-table -property Name, Permission -auto

Name                   Permission
----                   ----------
MaintenanceShell       Everyone AccessDenied, BUILTIN\Administrators AccessAllowed
microsoft.powershell   BUILTIN\Administrators AccessAllowed
microsoft.powershell32 BUILTIN\Administrators AccessAllowed

C:\PS> Set-PSSessionConfiguration -name MaintenanceShell -MaximumReceivedDataSizePerCommandMB 60

ParamName            ParamValue
---------            ----------
psmaximumreceived... 60

"Restart WinRM service"
WinRM service need to be restarted to make the changes effective. Do you want to run the command "restart-service winrm"?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): y

C:\PS> new-pssession -computername localhost -configurationName MaintenanceShell

[localhost] Connecting to remote server failed with the following error message : Access is denied. For more information, see the about_Remote_Troubl
eshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionOpenFailed

Description
-----------
This example shows the effect of disabling a session configuration.

The first command uses the Get-SessionConfiguration and Format-Table cmdlets to display only the Name and Permission properties of the session configuration objects. This table format makes it easier to see the values of the objects. The results show that members of the Administrators group are permitted to use the session configurations.

The second command uses the Disable-PSSessionConfiguration cmdlet to disable the MaintenanceShell session configuration. The command uses the Force parameter to suppress all user prompts.

The third command repeats the first command. The results show that you can still get the object that represents the MaintenanceShell session configuration even though everyone is denied access to it. The "AccessDenied" entry takes precedence over all other entries in the security descriptor.

The fourth command uses the Set-PSSessionConfiguration cmdlet to increase the MaximumDataSizePerCommandMB setting on the MaintenanceShell session configuration to 60. The results show that the command was successful even though everyone is denied access to the configuration.

The fifth command attempts to use the MaintenanceShell session configuration in a session. It uses the New-PSSession cmdlet to create a new session and the ConfigurationName parameter to specify the MaintenanceShell configuration. The results show that the  New-PSSession command fails because the user is denied access to the configuration.

See Also

  • about_Session_Configurations
  • Enable-PSSessionConfiguration
  • Get-PSSessionConfiguration
  • Register-PSSessionConfiguration
  • Set-PSSessionConfiguration
  • Unregister-PSSessionConfiguration
  • WS-Management Provider


Disable-WSManCredSSP

Disables Credential Security Service Provider (CredSSP) authentication on a client computer.

Syntax

Disable-WSManCredSSP [-Role] <string> [<CommonParameters>]

Description

The Disable-WSManCredSPP cmdlet disables CredSSP authentication on a client or on a server computer. When CredSSP authentication is used, the user's credentials are passed to a remote computer to be authenticated. This type of authentication is designed for commands that create a remote session from within another remote session. For example, you use this type of authentication if you want to run a background job on a remote computer.

The cmdlet is used to disable CredSSP on the client by specifying Client in the Role parameter. The cmdlet then performs the following:

- Disables CredSSP on the client. The WS-Management setting <localhost|computername>\Client\Auth\CredSSP is set to false.

- Removes any WSMan/* setting from the Windows CredSSP policy AllowFreshCredentials on the client.

The cmdlet is used to disable CredSSP on the server by specifying Server in the Role parameter. The cmdlet then performs the following:

- Disables CredSSP on the server. The WS-Management setting <localhost|computername>\Service\Auth\CredSSP is set to false.

Caution: CredSSP authentication delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

To disable CredSSP authentication, use the Disable-WSManCredSSP cmdlet.

Parameters

-Role <string>

Accepts one of two possible values: Client or Server. These values specify whether CredSSP should be disabled as a client or as a server.

If the cmdlet is used to disable CredSSP on the client by specifying Client in the Role parameter, then the cmdlet performs the following:

- Disables CredSSP on the client. The WS-Management setting <localhost|computername>\Client\Auth\CredSSP is set to false.

- Removes any WSMan/* setting from the Windows CredSSP policy AllowFreshCredentials on the client.

If the cmdlet is used to disable CredSSP on the server by specifying Server in the Role parameter, the cmdlet performs the following:

- Disables CredSSP on the server. The WS-Management setting <localhost|computername>\Service\Auth\CredSSP is set to false.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Notes

To enable CredSSP authentication, use the Enable-WSManCredSSP cmdlet.

Example 1

C:\PS>Disable-WSManCredSSP -Role Client

This command disables CredSSP on the client, which prevents delegation to servers.

Example 2

C:\PS>Disable-WSManCredSSP -Role Server

This command disables CredSSP on the server, which prevents delegation from clients.

See Also

  • Connect-WSMan
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


Disconnect-WSMan

Disconnects the client from the WinRM service on a remote computer.

Syntax

Disconnect-WSMan [-ComputerName <string>] [<CommonParameters>]

Description

The Disconnect-WSMan cmdlet disconnects the client from the WinRM service on a remote computer. If you saved the WS-Management session in a variable, the session object remains in the variable, but the state of the WS-Management session is "Closed". You can use this cmdlet within the context of the WS-Management Provider to disconnect the client from the WinRM service on a remote computer. However, you can also use this cmdlet to disconnect from the WinRM service on remote computers before you change to the WS-Management Provider.

For more information about how to connect to the WinRM service on a remote computer, see Connect-WSMan.

Parameters

-ComputerName <string>

Specifies the computer from which you want to disconnect. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

Note: You cannot disconnect from the local host (the default connection to the local computer). However, if a separate connection is made to the local computer (for example, by using the computer name), you can remove that connection by using the Disconnect-WSMan cmdlet .

Required? | false
Position? | named
Default Value | localhost
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>Disconnect-WSMan -computer server01

C:\PS> cd WSMan:
PS WSMan:\>
PS WSMan:\> dir

   WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName                                  Type
------------                                  ----
localhost                                     Container

Description
-----------
This command deletes the connection to the remote server01 computer.

This cmdlet is generally used within the context of the WS-Management provider to disconnect from a remote computer, in this case the server01 computer. However, you can also use the Disconnect-WSMan cmdlet to remove connections to remote computers before you  change to the WSMan provider. Those connections will not appear in the ComputerName list.

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


Enable-ComputerRestore

Enables the System Restore feature on the specified file system drive.

Syntax

Enable-ComputerRestore [-Drive] <string[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Enable-ComputerRestore cmdlet turns on the System Restore feature on one or more file system drives. As a result, you can use tools, such as the Restore-Computer cmdlet, to restore the computer to a previous state.

By default, System Restore is enabled on all eligible drives, but you can disable it, such as by using the Disable-ComputerRestore cmdlet. To enable (or re-enable) System Restore on any drive, it must be enabled on the system drive, either first or concurrently. To find the state of System Restore for each drive, use Rstrui.exe.

Parameters

-Drive <string[]>

Specifies the file system drives. Enter one or more file system drive letters, each followed by a colon and a backslash and enclosed in quotation marks, such as "C:\" or "D:\". This parameter is required.

You cannot use this cmdlet to enable System Restore on a remote network drive, even if the drive is mapped to the local computer, and you cannot enable System Restore on drives that are not eligible for System Restore, such as external drives.

To enable System Restore on any drive, System Restore must be enabled on the system drive, either before or concurrently.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to this cmdlet.
Outputs | None This cmdlet does not generate any output.

Notes

Disable-ComputerRestore and Enable-ComputerRestore work only on client operating systems, such as Windows Vista and Windows XP.

To run an Enable-ComputerRestore command on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administrator" option.

To find the file system drives that are eligible for system restore, in System in Control Panel, see the System Protection tab. To open this tab in Windows PowerShell, type "SystemPropertiesProtection".

This cmdlet uses the Windows Management Instrumentation (WMI) SystemRestore class.

Example 1

C:\PS>enable-computerrestore -drive "C:\"

This command enables System Restore on the C: drive of the local computer.

Example 2

C:\PS>enable-computerrestore -drive "C:\", "D:\"

This command enables System Restore on the C: and D: drives of the local computer.

See Also

  • Disable-ComputerRestore
  • Get-ComputerRestorePoint
  • Restore-Computer
  • Restart-Computer


Enable-PSBreakpoint

Enables the breakpoints in the current console.

Syntax

Enable-PSBreakpoint [-Id] <Int32[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Enable-PSBreakpoint [-Breakpoint] <Breakpoint[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Enable-PSBreakpoint cmdlet re-enables disabled breakpoints. You can use it to enable all breakpoints, or you can specify breakpoints by submitting breakpoint objects or breakpoint IDs.

A breakpoint is a point in a script where execution stops temporarily so that you can examine the instructions in the script. Newly created breakpoints are automatically enabled, but you can disable them by using the Disable-PSBreakpoint cmdlet.

Technically, this cmdlet changes the value of the Enabled property of a breakpoint object to True.

Enable-PSBreakpoint is one of several cmdlets designed for debugging Windows PowerShell scripts. For more information about the Windows PowerShell debugger, see about_Debuggers.

Parameters

-Breakpoint <Breakpoint[]>

Specifies the breakpoints to enable. Enter a variable that contains breakpoint objects or a command that gets breakpoint objects, such as a Get-PSBreakpoint command. You can also pipe breakpoint objects to Enable-PSBreakpoint.

Required? | true
Position? | 1
Default Value | None.
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Id <Int32[]>

Enables breakpoints that have the specified breakpoint IDs. The default value is all breakpoints. Enter the IDs or a variable that contains the IDs. (You cannot pipe IDs to Enable-PSBreakpoint.) To find the ID of a breakpoint, use the Get-PSBreakpoint cmdlet.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the enabled breakpoint. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | No output
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.Breakpoint You can pipe a breakpoint object to Enable-PSBreakpoint.
Outputs | None or System.Management.Automation.Breakpoint When you use the PassThru parameter, Enable-PSBreakpoint returns a breakpoint object that represent that breakpoint that was enabled. Otherwise, this cmdlet does not generate any output.

Notes

The Enable-PSBreakpoint cmdlet does not generate an error if you try to enable a breakpoint that is already enabled. As such, you can enable all breakpoints without error, even when only a few are disabled.

Breakpoints are enabled when you create them by using the Set-PSBreakpoint cmdlet. You do not need to enable newly created breakpoints.

Example 1

C:\PS>get-psbreakpoint | enable-psbreakpoint

This command enables all breakpoints in the current console. You can abbreviate the command as "gbp | ebp".

Example 2

C:\PS>enable-psbreakpoint -id 0, 1, 5

This command enables breakpoints with breakpoint IDs 0, 1, and 5.

Example 3

C:\PS>$b = set-psbreakpoint -script sample.ps1 -variable Name

C:\PS> $b | disable-psbreakpoint -passthru

AccessMode : Write
Variable   : Name
Action     :
Enabled    : False
HitCount   : 0
Id         : 0
Script     : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1

C:\PS> $b | enable-psbreakpoint -passthru

AccessMode : Write
Variable   : Name
Action     :
Enabled    : True
HitCount   : 0
Id         : 0
Script     : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1

Description
-----------
These commands re-enable a breakpoint that has been disabled.

The first command uses the Set-PSBreakpoint cmdlet to create a breakpoint on the "Name" variable in the Sample.ps1 script. Then, it saves the breakpoint object in the $b variable.

The second command uses the Disable-PSBreakpoint cmdlet to disable the new breakpoint. It uses a pipeline operator (|) to send the breakpoint object in $b to the Disable-PSBreakpoint cmdlet, and it uses the PassThru parameter of Disable-PSBreakpoint to display the disabled breakpoint object. This lets you verify that the value of the Enabled property of the breakpoint object is False.

The third command uses the Enable-PSBreakpoint cmdlet to re-enable the breakpoint. It uses a pipeline operator (|) to send the breakpoint object in $b to the Enable-PSBreakpoint cmdlet, and it uses the PassThru parameter of Enable-PSBreakpoint to display the breakpoint object. This lets you verify that the value of the Enabled property of the breakpoint object is True.

The results are shown in the following sample output.

Example 4

C:\PS>$b = get-psbreakpoint -id 3, 5

C:\PS> enable-psbreakpoint -breakpoint $b

These commands enable a set of breakpoints by specifying their breakpoint objects.

The first command uses the Get-PSBreakpoint cmdlet to get the breakpoints and saves them in the $b variable.

The second command uses the Enable-PSBreakpoint cmdlet and its Breakpoint parameter to enable the breakpoints.
This command is the equivalent of "enable-psbreakpoint -id 3, 5".

See Also

  • about_Debuggers
  • Set-PSBreakpoint
  • Disable-PSBreakpoint
  • Get-PSBreakpoint
  • Remove-PSBreakpoint
  • Get-PSCallStack


Enable-PSRemoting

Configures the computer to receive remote commands.

Syntax

Enable-PSRemoting [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Enable-PSRemoting cmdlet configures the computer to receive Windows PowerShell remote commands that are sent by using the WS-Management technology.

You need to run this command only once on each computer that will receive commands. You do not need to run it on computers that only send commands. Because the configuration activates listeners, it is prudent to run it only where it is needed.

The Enable-PSRemoting cmdlet performs the following operations:

-- Runs the Set-WSManQuickConfig cmdlet, which performs the following tasks:

----- Starts the WinRM service.

----- Sets the startup type on the WinRM service to Automatic.

----- Creates a listener to accept requests on any IP address.

----- Enables a firewall exception for WS-Management communications.

-- Enables all registered Windows PowerShell session configurations to receive instructions from a remote computer.

----- Registers the "Microsoft.PowerShell" session configuration, if it is not already registered.

----- Registers the "Microsoft.PowerShell32" session configuration on 64-bit computers, if it is not already registered.

----- Removes the "Deny Everyone" setting from the security descriptor for all the registered session configurations.

----- Restarts the WinRM service to make the preceding changes effective.

To run this cmdlet on Windows Vista, Windows Server 2008, and later versions of Windows, you must start Windows PowerShell with the "Run as administrator" option.

Parameters

-Force

Suppresses all user prompts. By default, you are prompted to confirm each operation.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.String Enable-PSRemoting returns strings that describe its results.

Example 1

C:\PS>enable-psremoting

This command configures the computer to receive remote commands.

Example 2

C:\PS>enable-psremoting -force

This command configures the computer to receive remote commands. It uses the Force parameter to suppress the user prompts.

See Also

  • about_Remote
  • about_Session_Configurations
  • Disable-PSRemoting
  • Get-PSSessionConfiguration
  • Enable-PSSessionConfiguration
  • Disable-PSSessionConfiguration
  • Register-PSSessionConfiguration
  • Set-PSSessionConfiguration
  • WS-Management Provider


Enable-PSSessionConfiguration

Enables the session configurations on the local computer.

Syntax

Enable-PSSessionConfiguration [[-Name] <string[]>] [-Force] [-SecurityDescriptorSDDL <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Enable-PSSessionConfiguration cmdlet re-enables registered session configurations that have been disabled by using the Disable-PSSessionConfiguration cmdlet. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users.

Without parameters, Enable-PSSessionConfiguration re-enables the Microsoft.PowerShell configuration, which is the default configuration that is used for sessions.

This cmdlet performs the following operations for each enabled configuration:

-- Removes the "deny all" setting from the security descriptor of the configuration or replaces the security descriptor with one that you specify.

-- Turns on the listener that accepts requests on any IP address.

-- Restarts the WinRM service.

The Enable-PSSessionConfiguration cmdlet calls the Set-WSManQuickConfig cmdlet. However, it should not be used to enable remoting on the computer. Instead, use the more comprehensive cmdlet, Enable-PSRemoting.

Parameters

-Force

Suppresses all user prompts, and restarts the WinRM service without prompting. Restarting the service makes the configuration change effective.

To prevent a restart and suppress the restart prompt, use the NoServiceRestart parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of session configurations to enable. Enter one or more configuration names. Wildcards are permitted.

You can also pipe a string that contains a configuration name or a session configuration object to Enable-PSSessionConfiguration.

If you omit this parameter, Enable-PSSessionConfiguration enables the Microsoft.PowerShell session configuration.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | true

-SecurityDescriptorSDDL <string>

Replaces the security descriptor on the session configuration with the specified security descriptor.

If you omit this parameter, Enable-PSSessionConfiguration just deletes the "deny all" item from the security descriptor.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration, System.String You can pipe a session configuration object or a string that contains the name of a session configuration to Enable-PSSessionConfiguration.
Outputs | None This cmdlet does not return any objects.

Notes

To run this cmdlet on Windows Vista, Windows Server 2008, and later versions of Windows, you must start Windows PowerShell with the "Run as administrator" option.

Example 1

C:\PS>Enable-PSSessionConfiguration

This command re-enables the Microsoft.PowerShell default session configuration on the computer.

Example 2

C:\PS>Enable-PSSessionConfiguration -name MaintenanceShell, AdminShell

This command re-enables the MaintenanceShell and AdminShell session configurations on the computer.

Example 3

C:\PS>Enable-PSSessionConfiguration -name *

C:\PS> Get-PSSessionConfiguration | Enable-PSSessionConfiguration

Description
-----------
These commands re-enable all session configurations on the computer. The commands are equivalent, so you can use either one.

Enable-PSSessionConfiguration does not generate an error if you enable a session configuration that is already enabled.

Example 4

C:\PS>Enable-PSSessionConfiguration -name MaintenanceShell -securityDescriptorSDDL "O:NSG:BAD:P(A;;GXGWGR;;;BA)(A;;GAGR;;;S-1-5-21-123456789-188441444-3100496)S:P"

This command re-enables the MaintenanceShell session configuration and specifies a new security descriptor for the configuration.

See Also

  • about_Session_Configurations
  • Disable-PSSessionConfiguration
  • Get-PSSessionConfiguration
  • Register-PSSessionConfiguration
  • Set-PSSessionConfiguration
  • Unregister-PSSessionConfiguration
  • WS-Management Provider


Enable-WSManCredSSP

Enables Credential Security Service Provider (CredSSP) authentication on a client computer.

Syntax

Enable-WSManCredSSP [-Role] <string> [[-DelegateComputer] <string>] [<CommonParameters>]

Description

The Enable-WSManCredSPP cmdlet enables CredSSP authentication on a client or on a server computer. When CredSSP authentication is used, the user's credentials are passed to a remote computer to be authenticated. This type of authentication is designed for commands that create a remote session from within another remote session. For example, you use this type of authentication if you want to run a background job on a remote computer.

This cmdlet is used to enable CredSSP on the client by specifying Client in the Role parameter. The cmdlet then performs the following:

- Enables CredSSP on the client. The WS-Management setting <localhost|computername>\Client\Auth\CredSSP is set to true.

- Sets the Windows CredSSP policy AllowFreshCredentials to WSMan/Delegate on the client.

- Note: These settings allow the client to delegate explicit credentials to a server when server authentication is achieved.

This cmdlet is used to enable CredSSP on the server by specifying Server in the Role parameter. The cmdlet then performs the following:

- Enables CredSSP on the server. The WS-Management setting <localhost|computername>\Service\Auth\CredSSP is set to true.

- Note: This policy setting allows the server to act as a delegate for clients.

Caution: CredSSP authentication delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

To disable CredSSP authentication, use the Disable-WSManCredSSP cmdlet.

Parameters

-DelegateComputer <string>

Allows the client credentials to be delegated to the server or servers that are specified by this parameter. The value of this parameter should be a fully qualified domain name.

If the Role parameter specifies Client, the DelegateComputer parameter is mandatory.

If the Role parameter specifies Server, the DelegateComputer parameter is not allowed.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Role <string>

Accepts one of two possible values: Client or Server. These values specify whether CredSSP should be enabled as a client or as a server.

If the Role parameter specifies Client, the cmdlet performs the following:

- Enables CredSSP on the client. The WS-Management setting <localhost|computername>\Client\Auth\CredSSP is set to true.

- Sets the Windows CredSSP policy AllowFreshCredentials to WSMan/Delegate on the client.

- Note: These settings allow the client to delegate explicit credentials to a server when server authentication is achieved.

If the Role parameter specifies the Server, the cmdlet performs the following:

- Enables CredSSP on the server. The WS-Management setting <localhost|computername>\Service\Auth\CredSSP is set to true.

- Note: This policy setting allows the server to act as a delegate for clients.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | System.Xml.XmlElement If CredSSP authentication is successfully enabled, this cmdlet generates an XMLElement object.

Example 1

C:\PS>enable-wsmancredssp -role client -delegatecomputer server02.accounting.fabrikam.com

cfg         : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth
lang        : en-US
Basic       : true
Digest      : true
Kerberos    : true
Negotiate   : true
Certificate : true
CredSSP     : true

Description
-----------
This command allows the client credentials to be delegated to the server02 computer.

Example 2

C:\PS>enable-wsmancredssp -role client -delegatecomputer *.accounting.fabrikam.com

cfg         : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth
lang        : en-US
Basic       : true
Digest      : true
Kerberos    : true
Negotiate   : true
Certificate : true
CredSSP     : true

Description
-----------
This command allows the client credentials to be delegated to all the computers in the accounting.fabrikam.com domain.

Example 3

C:\PS>enable-wsmancredssp -role client -delegatecomputer server02.accounting.fabrikam.com, server03.accounting.fabrikam.com, server04.accounting.fabrikam.com

cfg         : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth
lang        : en-US
Basic       : true
Digest      : true
Kerberos    : true
Negotiate   : true
Certificate : true
CredSSP     : true

Description
-----------
This command allows the client credentials to be delegated to multiple computers.

Example 4

C:\PS>enable-wsmancredssp -role server

This command allows a computer to act as a delegate for another. The Enable-WSManCredSSP cmdlet (shown in the earlier examples) only enables CredSSP authentication on the client, and specifies the remote computers that can act on it's behalf. In order for the remote computer to act as a delegate for the client, the CredSSP item in the Service node of WSMan must be set to true.

Example 5

C:\PS>connect-wsman server02
set-item wsman:\server02\service\auth\credSSP -value $true

This command allows a computer to act as a delegate for another computer. The Enable-WSManCredSSP commands that are shown in the earlier examples enable CredSSP authentication only on the client computer, and they specify the remote computers that can act on behalf of the client computer. For the remote computer to act as a delegate for the client computer, the CredSSP item in the Service directory of the WSMan provider must be set to true.

In this example, the first command creates a connection to the remote server02 computer.

The second command sets the credSSP value on the remote server02 computer, which allows the remote computer to act as a delegate.

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


Enter-PSSession

Starts an interactive session with a remote computer.

Syntax

Enter-PSSession [-ComputerName] <string> [-ApplicationName <string>] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-Port <int>] [-SessionOption <PSSessionOption>] [-UseSSL] [<CommonParameters>]

Enter-PSSession [[-Id] <int>] [<CommonParameters>]

Enter-PSSession [-InstanceId <Guid>] [<CommonParameters>]

Enter-PSSession [-Name <string>] [<CommonParameters>]

Enter-PSSession [[-Session] <PSSession>] [<CommonParameters>]

Enter-PSSession [[-ConnectionURI] <Uri>] [-AllowRedirection] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-SessionOption <PSSessionOption>] [<CommonParameters>]

Description

The Enter-PSSession cmdlet starts an interactive session with a single remote computer. During the session, the commands that you type run on the remote computer, just as though you were typing directly on the remote computer. You can have only one interactive session at a time.

Typically, you use the ComputerName parameter to specify the name of the remote computer. However, you can also use a session that you create by using New-PSSession for the interactive session.

To end the interactive session and disconnect from the remote computer, use the Exit-PSSession cmdlet, or type "exit".

Parameters

-AllowRedirection

Allows redirection of this connection to an alternate Uniform Resource Identifier (URI).

When you use the ConnectionURI parameter, the remote destination can return an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use this parameter to allow it to redirect the connection.

Allows redirection of this connection to an alternate URI.

When you use the ConnectionURI parameter, the remote destination can return an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use the AllowRedirection parameter to allow it to redirect the connection.

You can also limit the number of times that the connection is redirected by setting the MaximumConnectionRedirectionCount property of the $PSSessionOption preference variable, or the MaximumConnectionRedirectionCount property of the value of the SessionOption parameter. The default value is 5. For more information, see the description of the SessionOption parameter, and see New-PSSessionOption.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ApplicationName <string>

Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the ConnectionURI parameter in the command.

The default value is the value of the $PSSessionApplicationName preference variable on the local computer. If this preference variable is not defined, the default value is WSMAN. This value is appropriate for most uses. For more information, see about_Preference_Variables.

The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the URLPrefix property of a listener on the remote computer.

Required? | false
Position? | named
Default Value | WSMAN
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Authentication <AuthenticationMechanism>

Specifies the mechanism that is used to authenticate the user's credentials. Valid values are "Default", "Basic", "Credssp", "Digest", "Kerberos", "Negotiate", and "NegotiateWithImplicitCredential". The default value is "Default".

CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows.

For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=144382.

Caution: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CertificateThumbprint <string>

Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate.

Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts.

To get a certificate thumbprint, use the Get-Item or Get-ChildItem command in the Windows PowerShell Cert: drive.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Starts an interactive session with the specified remote computer. Enter only one computer name. The default is the local computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more remote computers. You can also pipe a computer name to Enter-PSSession.

To use an IP address in the value of the ComputerName parameter, the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_Troubleshooting.

Note: In Windows Vista and later versions of Windows, to include the local computer in the value of the ComputerName parameter, you must start Windows PowerShell with the "Run as administrator" option.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-ConfigurationName <string>

Specifies the session configuration that is used for the interactive session.

Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: http://schemas.microsoft.com/powershell.

The session configuration for a session is located on the remote computer. If the specified session configuration does not exist on the remote computer, the command fails.

The default value is the value of the $PSSessionConfigurationName preference variable on the local computer. If this preference variable is not set, the default is Microsoft.PowerShell. For more information, see about_Preference_Variables.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-ConnectionURI <Uri>

Specifies a Uniform Resource Identifier (URI) that defines the connection endpoint for the interactive session. The URI must be fully qualified.

The format of this string is as follows:

<Transport>://<ComputerName>:<Port>/<ApplicationName>

The default value is as follows:

http://localhost:80/WSMAN

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you do not specify a ConnectionURI, you can use the UseSSL, ComputerName, Port, and ApplicationName parameters to specify the URI values.

If the destination computer redirects the connection to a different URI, Windows PowerShell prevents the redirection unless you use the AllowRedirection parameter in the command.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01", "Domain01\User01", or "User@Domain.com", or enter a PSCredential object, such as one returned by the Get-Credential cmdlet.

When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | Current user
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Id <int>

Specifies the ID of an existing session. Enter-PSSession uses the specified session for the interactive session.

To find the ID of a session, use the Get-PSSession cmdlet.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InstanceId <Guid>

Specifies the instance ID of an existing session. Enter-PSSession uses the specified session for the interactive session.

The instance ID is a GUID. To find the instance ID of a session, use the Get-PSSession cmdlet. You can also use the Session, Name, or ID parameters to specify an existing session. Or, you can use the ComputerName parameter to start a temporary session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string>

Specifies the friendly name of an existing session. Enter-PSSession uses the specified session for the interactive session.

If the name that you specify matches more than one session, the command fails. You can also use the Session, InstanceID, or ID parameters to specify an existing session. Or, you can use the ComputerName parameter to start a temporary session.

To establish a friendly name for a session, use the Name parameter of the New-PSSession cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Port <int>

Specifies the network port on the remote computer used for this command. The default is port 80 (the HTTP port).

Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. Use the following commands to configure the listener:

1. winrm delete winrm/config/listener?Address=*+Transport=HTTP

2. winrm create winrm/config/listener?Address=*+Transport=HTTP @{Port="<port-number>"}

Do not use the Port parameter unless you must. The port setting in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Session <PSSession>

Specifies a Windows PowerShell session (PSSession) to use for the interactive session. This parameter takes a session object. You can also use the Name, InstanceID, or ID parameters to specify a PSSession.

Enter a variable that contains a session object or a command that creates or gets a session object, such as a New-PSSession or Get-PSSession command. You can also pipe a session object to Enter-PSSession. You can submit only one PSSession with this parameter. If you enter a variable that contains more than one PSSession, the command fails.

When you use Exit-PSSession or the EXIT keyword, the interactive session ends, but the PSSession that you created remains open and available for use.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | true

-SessionOption <PSSessionOption>

Sets advanced options for the session. Enter a SessionOption object that you create by using the New-PSSessionOption cmdlet.

The default values for the options are determined by the value of the $PSSessionOption preference variable, if it is set. Otherwise, the session uses the system defaults.

For a description of the session options, including the default values, see New-PSSessionOption. For information about the $PSSessionOption preference variable, see about_Preference_Variables.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all Windows PowerShell content transmitted over the network. UseSSL is an additional protection that sends the data across an HTTPS connection instead of an HTTP connection.

If you use this parameter, but SSL is not available on the port used for the command, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String or System.Management.Automation.Runspaces.PSSession You can pipe a computer name (a string) or a session object to Enter-PSSession.
Outputs | None The cmdlet does not return any output.

Notes

-- To connect to a remote computer, you must be a member of the Administrators group on the remote computer.

-- In Windows Vista and later versions of Windows, to start an interactive session on the local computer, you must start Windows PowerShell with the "Run as administrator" option.

-- When you use Enter-PSSession, your user profile on the remote computer is used for the interactive session. The commands in the remote user profile, including commands to add Windows PowerShell snap-ins and to change the command prompt, run before the remote prompt is displayed.

-- Enter-PSSession uses the UI culture setting on the local computer for the interactive session. To find the local UI culture, use the $UICulture automatic variable.

-- Enter-PSSession requires the Get-Command, Out-Default, and Exit-PSSession cmdlets. If these cmdlets are not included in the session configuration on the remote computer, the Enter-PSSession commands fails.

-- Unlike Invoke-Command, which parses and interprets the commands before sending them to the remote computer, Enter-PSSession sends the commands directly to the remote computer without interpretation.

Example 1

C:\PS>Enter-PSSession

LocalHost\PS>

Description
-----------
This command starts an interactive session on the local computer. The command prompt changes to indicate that you are now running commands in a different session.

The commands that you enter run in the new session, and the results are returned to the default session as text.

Example 2

C:\PS>enter-pssession -computer Server01

Server01\PS> get-process powershell > C:\ps-test\process.txt

Server01\PS> exit-pssession
C:\PS>

C:\PS> dir C:\ps-test\process.txt
Get-ChildItem : Cannot find path 'C:\ps-test\process.txt' because it does not exist.
At line:1 char:4
+ dir <<<<  c:\ps-test\process.txt

Description
-----------
This command shows how to work in an interactive session with a remote computer.

The first command uses the Enter-PSSession cmdlet to start an interactive session with Server01, a remote computer. When the session starts, the command prompt changes to include the computer name.

The second command gets the PowerShell process and redirects the output to the Process.txt file. The command is submitted to the remote computer, and the file is saved on the remote computer.

The third command uses the Exit keyword to end the interactive session and close the connection.

The fourth command confirms that the Process.txt file is on the remote computer. A Get-ChildItem ("dir") command on the local computer cannot find the file.

Example 3

C:\PS>$s = new-pssession -computername Server01

C:\PS> Enter-PSSession -session $s

Server01\PS>

Description
-----------
These commands use the Session parameter of Enter-PSSession to run the interactive session in an existing Windows PowerShell session (PSSession).

Example 4

C:\PS>Enter-PSSession -computername Server01 -port 90 -credential domain01\user01

Server01\PS>

Description
-----------
This command starts an interactive session with the Server01 computer. It uses the Port parameter to specify the port and the Credential parameter to specify the account of a user with permission to connect to the remote computer.

Example 5

C:\PS>Enter-PSSession -computername Server01

Server01:\PS> Exit-PSSession

C:\PS>

Description
-----------
This example shows how to start and stop an interactive session. The first command uses the Enter-PSSession cmdlet to start an interactive session with the Server01 computer.

The second command uses the Exit-PSSession cmdlet to end the session. You can also use the Exit keyword to end the interactive session. Exit-PSSession and Exit have the same effect.

See Also

  • about_PSSessions
  • about_Remote
  • New-PSSession
  • Get-PSSession
  • Exit-PSSession
  • Remove-PSSession
  • Invoke-Command


Exit-PSSession

Ends an interactive session with a remote computer.

Syntax

Exit-PSSession [<CommonParameters>]

Description

The Exit-PSSession cmdlet ends interactive sessions that you started by using Enter-PSSession.

You can also use the Exit keyword to end an interactive session. The effect is the same as using Exit-PSSession.

Parameters

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Exit-PSSession.
Outputs | None This cmdlet does not return any output.

Notes

This cmdlet takes only the common parameters.

Example 1

C:\PS>Enter-PSSession -computername Server01

Server01\PS> Exit-PSSession

C:\PS>

Description
-----------
These commands start and then stop an interactive session with the Server01 remote computer.

Example 2

C:\PS>$s = new-pssession -computername Server01

C:\PS> Enter-PSSession -session $s

Server01\PS> Exit-PSSession

C:\PS> $s

Id Name            ComputerName    State    ConfigurationName
-- ----            ------------    -----    -----------------
1  Session1        Server01        Opened   Microsoft.PowerShell

Description
-----------
These commands start and stop an interactive session with the Server01 computer that uses a Windows PowerShell session (PSSession).

Because the interactive session was started by using a Windows PowerShell session (PSSession), the PSSession is still available when the interactive session ends. If you use the ComputerName parameter, Enter-PSSession creates a temporary session that it closes when the interactive session ends.

The first command uses the New-PSSession cmdlet to create a PSSession on the Server01 computer. The command saves the PSSession in the $s variable.

The second command uses the Enter-PSSession cmdlet to start an interactive session using the PSSession in $s.

The third command uses the Exit-PSSession cmdlet to stop the interactive session.

The final command displays the PSSession in the $s variable. The State property shows the PSSession is still open and available for use.

Example 3

C:\PS>Enter-PSSession -computername Server01

Server01\PS> exit

C:\PS>

This command uses the Exit keyword to stop an interactive session started by using the Enter-PSSession cmdlet. The Exit keyword has the same effect as using Exit-PSSession.

See Also

  • about_PSSessions
  • about_Remote
  • Enter-PSSession
  • New-PSSession
  • Get-PSSession
  • Remove-PSSession
  • Invoke-Command


Export-Alias

Exports information about currently defined aliases to a file.

Syntax

Export-Alias [-Path] <string> [[-Name] <string[]>] [-Append] [-As {<Csv> | <Script>}] [-Description <string>] [-Force] [-NoClobber] [-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Export-Alias cmdlet exports the aliases in the current session to a file. If the output file does not exist, the cmdlet will create it.

Export-Alias can export the aliases in a particular scope or all scopes, it can generate the data in CSV format or as a series of Set-Alias commands that you can add to a session or to a Windows PowerShell profile.

Parameters

-Append

Appends the output to the specified file, rather than overwriting the existing contents of that file.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-As <ExportAliasFormat>

Determines the output format. CSV is the default.

Valid values are:

-- CSV: Comma-separated value (CSV) format.

-- Script: Creates a Set-Alias command for each exported alias. If you name the output file with a .ps1 file name extension, you can run it as a script to add the aliases to any session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Description <string>

Adds a description to the exported file. The description appears as a comment at the top of the file, following the header information.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Overwrites the output file, even if the read-only attribute is set on the file.

By default, Export-Alias overwrites files without warning, unless the read-only or hidden attribute is set or the NoClobber parameter is used in the command. The NoClobber parameter takes precedence over the Force parameter when both are used in a command.

The Force parameter cannot force Export-Alias to overwrite files with the hidden attribute.

Required? | false
Position? | named
Default Value | Does not overwrite read-only files.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of the aliases to export. Wildcards are permitted.

By default, Export-Alias exports all aliases in the session or scope.

Required? | false
Position? | 2
Default Value | Export all aliases
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-NoClobber

Prevents Export-Alias from overwriting any files, even if the Force parameter is used in the command.

If the NoClobber parameter is omitted, Export-Alias will overwrite an existing file without warning, unless the read-only attribute is set on the file. NoClobber takes precedence over the Force parameter, which permits Export-Alias to overwrite a file with the read-only attribute.

NoClobber does not prevent the Append parameter from adding content to an existing file.

Required? | false
Position? | named
Default Value | Overwrites read-write files.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns objects that represent the aliases that were exported. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | No output
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the path to the output file. Wildcards are permitted, but the resulting path value must resolve to a single file name. This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Scope <string>

Specifies the scope from which the aliases should be exported.

Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | Local
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None. You cannot pipe objects to this cmdlet.
Outputs | None or System.Management.Automation.AliasInfo When you use the Passthru parameter, Export-Alias returns a System.Management.Automation.AliasInfo object that represents the alias. Otherwise, this cmdlet does not generate any output.

Notes

You can only Export-Aliases to a file.

Example 1

C:\PS>export-alias -path alias.csv

This command exports current alias information to a file named Alias.csv in the current directory.

Example 2

C:\PS>export-alias -path alias.csv -noclobber

This command exports the aliases in the current session to an Alias.csv file.

Because the NoClobber parameter is specified, the command will fail if an Alias.csv file already exists in the current directory.

Example 3

C:\PS>export-alias -path alias.csv -append -description "Appended Aliases" -force

This command appends the aliases in the current session to the Alias.csv file.

The command uses the Description parameter to add a description to the comments at the top of the file.

The command also uses the Force parameter to overwrite any existing Alias.csv files, even if they have the read-only attribute.

Example 4

C:\PS>export-alias -path alias.ps1 -as script

C:\PS> add-content -path $profile -value (get-content alias.ps1)

C:\PS> $s = new-pssession -computername Server01
C:\PS> invoke-command -session $s -filepath .\alias.ps1

This example shows how to use the script file format that Export-Alias generates.

The first command exports the aliases in the session to the Alias.ps1 file. It uses the As parameter with a value of Script to generate a file that contains a Set-Alias command for each alias.

The second command adds the aliases in the Alias.ps1 file to the CurrentUser-CurrentHost profile. (The path to the profile is saved in the $profile variable.) The command uses the Get-Content cmdlet to get the aliases from the Alias.ps1 file and the Add-Content cmdlet to add them to the profile. For more information, see about_Profiles.

The third and fourth commands add the aliases in the Alias.ps1 file to a  remote session on the Server01 computer. The third command uses the New-PSSession cmdlet to create the session. The fourth command uses the FilePath parameter of the Invoke-Command cmdlet to run the Alias.ps1 file in the new session.

See Also

  • Import-Alias
  • Get-Alias
  • New-Alias
  • Set-Alias


Export-Clixml

Creates an XML-based representation of an object or objects and stores it in a file.

Syntax

Export-Clixml [-Path] <string> -InputObject <psobject> [-Depth <int>] [-Encoding <string>] [-Force] [-NoClobber] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Export-Clixml cmdlet creates an XML-based representation of an object or objects and stores it in a file. You can then use the Import-CLIXML cmdlet to re-create the saved object based on the contents of that file.

This cmdlet is similar to ConvertTo-XML, except that Export-Clixml stores the resulting XML in a file. ConvertTo-XML returns the XML, so you can continue to process it in Windows PowerShell.

Parameters

-Depth <int>

Specifies how many levels of contained objects are included in the XML representation. The default value is 2.

The default value can be overridden for the object type in the Types.ps1xml files. For more information, see about_Types.ps1xml.

Required? | false
Position? | named
Default Value | 2
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Encoding <string>

Specifies the type of encoding for the target file. Valid values are ASCII, UTF8, UTF7, UTF32, Unicode, BigEndianUnicode, Default, and OEM. UTF8 is the default.

Required? | false
Position? | named
Default Value | UTF8
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Causes the cmdlet to clear the read-only attribute of the output file if necessary. The cmdlet will attempt to reset the read-only attribute when the command completes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the object to be converted. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe objects to Export-Clixml.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-NoClobber

Ensures that the cmdlet does not overwrite the contents of an existing file. By default, if a file exists in the specified path, Export-Clixml overwrites the file without warning.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the path to the file where the XML representation of the object will be stored.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Export-Clixml.
Outputs | System.IO.FileInfo Export-Clixml creates a file that contains the XML.

Example 1

C:\PS>"This is a test" | export-clixml sample.xml

This command creates an XML file that stores a representation of the string, "This is a test".

Example 2

C:\PS>get-acl C:\test.txt | export-clixml -Path fileacl.xml

C:\PS> $fileacl = import-clixml fileacl.xml

This example shows how to export an object to an XML file and then create an object by importing the XML from the file.

The first command uses the Get-ACL cmdlet to get the security descriptor of the Test.txt file. It uses a pipeline operator to pass the security descriptor to Export-Clixml, which stores an XML-based representation of the object in a file named FileACL.xml.

The second command uses the Import-Clixml cmdlet to create an object from the XML in the FileACL.xml file. Then, it saves the object in the $FileAcl variable.

See Also

  • Import-Clixml
  • ConvertTo-XML
  • Export-CSV
  • ConvertTo-Html


Export-Console

Exports the names of snap-ins in the current session to a console file.

Syntax

Export-Console [[-Path] <string>] [-Force] [-NoClobber] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Export-Console cmdlet exports the names of the Windows PowerShell snap-ins in the current session to a Windows PowerShell console file (.psc1). You can use this cmdlet to save the snap-ins for use in future sessions.

To add the snap-ins in the .psc1 console file to a session, start Windows PowerShell (Powershell.exe) at the command line by using Cmd.exe or another Windows PowerShell session, and then use the PSConsoleFile parameter of Powershell.exe to specify the console file.

For more information about Windows PowerShell snap-ins, see about_PSSnapins.

Parameters

-Force

Overwrites the data in a console file without warning, even if the file has the read-only attribute. The read-only attribute is changed and is not reset when the command completes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoClobber

Will not overwrite (replace the contents of) an existing console file. By default, if a file exists in the specified path, Export-Console overwrites the file without warning.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies a path and file name for the console file (*.psc1). Enter a path (optional) and name. Wildcards are not permitted.

If you type only a file name, Export-Console creates a file with that name and the ".psc1" file name extension in the current directory.

This parameter is required unless you have opened Windows PowerShell with the PSConsoleFile parameter or exported a console file during the current session. It is also required when you use the NoClobber parameter to prevent the current console file from being overwritten.

If you omit this parameter, Export-Console overwrites (replaces the content of) the console file that was used most recently in this session. The path to the most recently used console file is stored in the value of the $ConsoleFileName automatic variable. For more information, see about_Automatic_Variables.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a path string to Export-Console.
Outputs | System.IO.FileInfo Export-Console creates a file that contains the exported aliases.

Notes

When a console file (.psc1) is used to start the session, the name of the console file is automatically stored in the $ConsoleFileName automatic variable. The value of $ConsoleFileName is updated when you use the Path parameter of Export-Console to specify a new console file. When no console file is used, $ConsoleFileName has no value ($null).

To use a Windows PowerShell console file in a new session, use the following syntax to start Windows PowerShell:

"powershell.exe -PsConsoleFile <ConsoleFile>.psc1".

You can also save Windows PowerShell snap-ins for future sessions by adding an Add-PSSnapin command to your Windows PowerShell profile. For more information, see about_Profiles.

Example 1

C:\PS>export-console -path $pshome\Consoles\ConsoleS1.psc1

This command exports the names of Windows PowerShell snap-ins in the current session to the ConsoleS1.psc1 file in the Consoles subdirectory of the Windows PowerShell installation directory, $pshome.

Example 2

C:\PS>export-console

This command exports the names of Windows PowerShell snap-ins from current session to the Windows PowerShell console file that was most recently used in the current session. It overwrites the previous file contents.

If you have not exported a console file during the current session, you are prompted for permission to continue and then prompted for a file name.

Example 3

C:\PS>add-pssnapin NewPSSnapin

C:\PS> export-console -path NewPSSnapinConsole.psc1

C:\PS> powershell.exe -PsConsoleFile NewPsSnapinConsole.psc1

These commands add the NewPSSnapin Windows PowerShell snap-in to the current session, export the names of Windows PowerShell snap-ins in the current session to a console file, and then start a Windows PowerShell session with the console file.

The first command uses the Add-PSSnapin cmdlet to add the NewPSSnapin snap-in to the current session. You can only add Windows PowerShell snap-ins that are registered on your system.

The second command exports the Windows PowerShell snap-in names to the NewPSSnapinConsole.psc1 file.

The third command starts Windows PowerShell with the NewPSSnapinConsole.psc1 file. Because the console file includes the Windows PowerShell snap-in name, the cmdlets and providers in the snap-in are available in the current session.

Example 4

C:\PS>export-console -path Console01

C:\PS> notepad console01.psc1

<?xml version="1.0" encoding="utf-8"?>
<PSConsoleFile ConsoleSchemaVersion="1.0">
  <PSVersion>2.0</PSVersion>
  <PSSnapIns>
    <PSSnapIn Name="NewPSSnapin" />
  </PSSnapIns>
</PSConsoleFile>

Description
-----------
This command exports the names of the Windows PowerShell snap-ins in the current session to the Console01.psc1 file in the current directory.

The second command displays the contents of the Console01.psc1 file in Notepad.

Example 5

C:\PS>powershell.exe -PSConsoleFile Console01.psc1

C:\PS> add-pssnapin MySnapin

C:\PS> export-console NewConsole.psc1

C:\PS> $consolefilename

C:\PS> add-pssnapin SnapIn03

C:\PS> export-console

This example shows how to use the $ConsoleFileName automatic variable to determine the console file that will be updated if you use Export-Console without a Path parameter value.

The first command uses the PSConsoleFile parameter of PowerShell.exe to open Windows PowerShell with the Console01.psc1 file.

The second command uses the Add-PSSnapin cmdlet to add the MySnapin Windows PowerShell snap-in to the current session.

The third command uses the Export-Console cmdlet to export the names of all the Windows PowerShell snap-ins in the session to the NewConsole.psc1 file.

The fourth command uses the $ConsoleFileName parameter to display the most recently used console file. The sample output shows that NewConsole.ps1 is the most recently used file.

The fifth command adds SnapIn03 to the current console.

The sixth command uses the ExportConsole cmdlet without a Path parameter. This command exports the names of all the Windows PowerShell snap-ins in the current session to the most recently used file, NewConsole.psc1.

See Also

  • Add-PSSnapin
  • Get-PSSnapin
  • Remove-PSSnapin


Export-Counter

The Export-Counter cmdlet takes PerformanceCounterSampleSet objects and exports them as counter log files.

Syntax

Export-Counter [-Path] <string> -InputObject <PerformanceCounterSampleSet[]> [-Circular <switch>] [-FileFormat <string>] [-Force <switch>] [-MaxSize <int>] [<CommonParameters>]

Description

The Export-Counter cmdlet exports performance counter data (PerformanceCounterSampleSet objects) to log files in binary performance log (.blg), comma-separated value (.csv), or tab-separated value (.tsv) format. You can use this cmdlet to log or relog performance counter data.

Export-Counter is designed to export data that is returned by the Get-Counter and Import-Counter cmdlets.

Note: Export-Counter runs only on Windows 7, Windows Server 2008 R2, and later versions of Windows.

Parameters

-Circular <switch>

Indicates that output file should be a circular log with first in, first out (FIFO) format. When you include this parameter, the MaxSize parameter is required.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FileFormat <string>

Specifies the output format of the output log file. Valid values are CSV, TSV, and BLG. The default value is BLG.

Required? | false
Position? | named
Default Value | BLG
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force <switch>

Overwrites and replaces an existing file if one exists in the location specified by the Path parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <PerformanceCounterSampleSet[]>

Specifies the counter data to export. Enter a variable that contains the data or a command that gets the data, such as a Get-Counter or Import-Counter command.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-MaxSize <int>

Specifies the maximum size of the output file.

If the Circular parameter is specified, then when the log file reaches the specified maximum size, the oldest entries are deleted as newer ones are added. If the Circular parameter is not specified, then when the log file reaches the specified maximum size, no new data is added and the cmdlet generates a non-terminating error.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the path and file name of the output file. Enter a relative or absolute path on the local computer, or a Uniform Naming Convention (UNC) path to a remote computer, such as \\Computer\Share\file.blg. This parameter is required.

Note: The file format is determined by the value of the FileFormat parameter, not by the file name extension in the path.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet. You can pipe performance counter data from Get-Counter or Import-Counter to Export-Counter
Outputs | None None

Notes

The log file generator expects that all input objects have the same counter path and that the objects are arranged in ascending time order.

The counter type and path of the first input object determines the properties recorded in the log file. If other input objects do not have a value for a recorded property, the property field is empty. If the objects have property values that were not recorded, the extra property values are ignored.

Performance Monitor might not be able to read all logs that Export-Counter generates. For example, Performance Monitor requires that all objects have the same path and that all objects are separated by the same time interval.

The Import-Counter cmdlet does not have a ComputerName parameter. However, if the computer is configured for Windows PowerShell remoting, you can use the Invoke-Command cmdlet to run an Import-Counter command on a remote computer.

Example 1

C:\PS>get-counter "\Processor(*)\% Processor Time" -max 50 | export-counter -path $home\counters.blg

These commands export counter data to a .blg file.

The command uses the Get-Counter cmdlet to collect processor time data. It uses a pipeline operator (|) to send the data to the Export-Counter cmdlet. The Export-Counter command uses the Path variable to specify the output file.

Because the data set might be very large, this command sends the data to Export-Counter through the pipeline. If the data were saved in a variable, the command might use a disproportionate amount of memory.

Example 2

C:\PS>$1GBinBytes = 1GB

C:\PS> import-counter threads.csv | export-counter -path threadtest.blg -circular -maxsize $1GBinBytes

These commands convert a CSV file to a counter data BLG format.

The first command uses the built-in Windows PowerShell conversion feature to store the value of 1 gigabyte (GB) in bytes in the $1GBinBytes variable. When you type a value followed by K (kilobyte), MB (megabyte), or GB, Windows PowerShell returns the value in bytes.

The second command uses the Import-Counter cmdlet to import performance counter data from the Threads.csv file. The example presumes that this file was previously exported by using the Export-Counter cmdlet.

A pipeline operator (|) sends the imported data to the Export-Counter cmdlet. The command uses the Path parameter to specify the location of the output file. It uses the Circular and MaxSize parameters to direct Export-Counter to create a circular log that wraps at 1 GB.

Example 3

C:\PS>$c = get-counter -computername Server01 -counter "\Process(*)\Working Set - Private" -maxSamples 20

C:\PS> $c | export-counter -path \\Server01\Perf\WorkingSet.blg

This example shows how to get performance counter data from a remote computer and save the data in a file on the remote computer.

The first command uses the Get-Counter cmdlet to collect working set counter data from Server01, a remote computer. The command saves the data in the $c variable.

The second command uses a pipeline operator (|) to send the data in $c to the Export-Counter cmdlet, which saves it in the Workingset.blg file in the Perf share on the Server01 computer.

Example 4

C:\PS>$all = import-counter DiskSpace.blg

C:\PS> $lowSpace = $all.countersamples | where {$_.cookedvalues -lt 15}

C:\PS> $lowSpace | export-counter -path LowDiskSpace.blg

This example shows how to use the Import-Counter and Export-Counter cmdlets to relog existing data.

The first command uses the Import-Counter cmdlet to import performance counter data from the DiskSpace.blg log. It saves the data in the $all variable. This file contains samples of the "LogicalDisk\% Free Space" counter on more than 200 remote computers in the enterprise.

The second command uses the CounterSamples property of the sample set object in $all and the Where-Object cmdlet (alias = "where") to select objects with CookedValues of less than 15 (percent). The command saves the results in the $lowSpace variable.

The third command uses a pipeline operator (|) to send the data in the $lowSpace variable to the Export-Counter cmdlet. The command uses the path variable to indicate that the selected data should be logged in the LowDiskSpace.blg file.

See Also

  • Get-Counter
  • Import-Counter


Export-CSV

Converts Microsoft .NET Framework objects into a series of comma-separated value (CSV) variable-length strings and saves the strings in a CSV file.

Syntax

Export-CSV [[-Delimiter] <char>] [-Path] <string> -InputObject <psobject> [-Encoding <string>] [-Force] [-NoClobber] [-NoTypeInformation] [-Confirm] [-WhatIf] [<CommonParameters>]

Export-CSV [-UseCulture] [-Path] <string> -InputObject <psobject> [-Encoding <string>] [-Force] [-NoClobber] [-NoTypeInformation] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Export-CSV cmdlet creates a CSV variable-length file that represents the objects that you submit.

You can then use the Import-CSV cmdlet to re-create objects from the CSV strings in the files. The resulting objects are CSV versions of the original objects that consist of string representations of the property values and no methods.

You can also use the ConvertTo-CSV and ConvertFrom-CSV cmdlets to convert .NET Framework objects to CSV strings (and back). Export-CSV is the same as ConvertTo-CSV, except that it saves the CSV strings in a file.

You can use the parameters of the Export-CSV cmdlet to specify a delimiter other than a comma or to direct Export-CSV to use the default delimiter for the current culture.

When you submit multiple objects to Export-CSV, Export-CSV organizes the file based on the properties of the first object that you submit. If the remaining objects do not have one of the specified properties, the property value of that object is null, as represented by two consecutive commas. If the remaining objects have additional properties, those property values are not included in the file.

For more information, see Export-CSV, and see the Notes section.

Parameters

-Delimiter <char>

Specifies a delimiter to separate the property values. The default is a comma (,). Enter a character, such as a colon (:). To specify a semicolon (;), enclose it in quotation marks.

Required? | false
Position? | 2
Default Value | , (comma)
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Encoding <string>

Specifies the encoding for the exported CSV file. Valid values are Unicode, UTF7, UTF8, ASCII, UTF32, BigEndianUnicode, Default, and OEM. The default is ASCII.

Required? | false
Position? | named
Default Value | ASCII
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Overwrites the file specified in path without prompting.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to export as CSV strings. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe objects to Export-CSV.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-NoClobber

Do not overwrite (replace the contents) of an existing file. By default, if a file exists in the specified path, Export-CSV overwrites the file without warning.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoTypeInformation

Omits the type information from the CSV file. By default, the first line of the CSV file contains "#TYPE " followed by the fully-qualified name of the type of the .NET Framework object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the path to the CSV output file. The parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseCulture

Use the list separator for the current culture as the item delimiter. The default is a comma (,).

This parameter is very useful in scripts that are being distributed to users worldwide. To find the list separator for a culture, use the following command: (Get-Culture).TextInfo.ListSeparator.

Required? | false
Position? | named
Default Value | Comma
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any .NET Framework object to Export-CSV.
Outputs | System.String The CSV list is sent to the file designated in the Path parameter.

Notes

The Export-CSV cmdlet converts the objects that you submit into a series of CSV variable-length strings and saves them in the specified text file. You can use Export-CSV to save objects in a CSV file and then use the Import-CSV cmdlet to create objects from the text in the CSV file.

In the CSV file, each object is represented by a comma-separated list of the property values of the object. The property values are converted to strings (by using the ToString() method of the object), so they are generally represented by the name of the property value. Export-CSV does not export the methods of the object.

The format of an exported file is as follows:

-- The first line of the CSV file contains the string '#TYPE ' followed by the fully qualified name of the .NET Framework type of the object, such as #TYPE System.Diagnostics.Process. To suppress this line, use the NoTypeInformation parameter.

-- The next line of the CSV file represents the column headers. It contains a comma-separated list of the names of all the properties of the first object.

-- Additional lines of the file consist of comma-separated lists of the property values of each object.

Example 1

C:\PS>get-process wmiprvse | select-object basePriority,ID,SessionID,WorkingSet | export-csv -path data.csv

This command selects a few properties of the wmiprvse process and exports them to a CSV format file named data.csv.

Example 2

C:\PS>get-process | export-csv processes.csv

C:\PS> get-process | export-csv processes.csv

# In processes.csv

#TYPE System.Diagnostics.Process
__NounName,Name,Handles,VM,WS,PM,NPM,Path,Company,CPU,FileVersion,...
Process,powershell,626,201666560,76058624,61943808,11960,C:\WINDOWS...
Process,powershell,257,151920640,38322176,37052416,7836,C:\WINDOWS\...

Description
-----------
This command exports objects representing the processes on the computer to the Processes.csv file in the current directory. Because it does not specify a delimiter, a comma (,) is used to separate the fields in the file.

Example 3

C:\PS>get-process | export-csv processes.csv -Delimiter ";"

# In processes.csv

#TYPE System.Diagnostics.Process
__NounName;Name;Handles;VM;WS;PM;NPM;Path;Company;CPU;FileVersion;...
Process;powershell;626;201666560;76058624;61943808;11960;C:\WINDOWS...
Process;powershell;257;151920640;38322176;37052416;7836;C:\WINDOWS\...

Description
-----------
This command exports objects representing the processes on the computer to the Processes.csv file in the current directory. It uses the Delimiter parameter to specify the semicolon (;). As a result, the fields in the file are separated by semicolons.

Example 4

C:\PS>get-process | export-csv processes.csv -UseCulture

This command exports objects representing the processes on the computer to the Processes.csv file in the current directory. It uses the UseCulture parameter to direct Export-CSV to use the delimiter specified by the ListSeparator property of the current culture.

Example 5

C:\PS>get-process | export-csv processes.csv -NoTypeInformation

C:\PS> get-process | export-csv processes.csv -NoTypeInformation

# In processes.csv

__NounName,Name,Handles,VM,WS,PM,NPM,Path,Company,CPU,FileVersion,...
Process,powershell,626,201666560,76058624,61943808,11960,C:\WINDOWS...
Process,powershell,257,151920640,38322176,37052416,7836,C:\WINDOWS\...

Description
-----------
This command exports objects representing the processes on the computer to the Processes.csv file in the current directory. It uses the NoTypeInformation parameter to suppress the type information in the file.

See Also

  • Import-CSV
  • ConvertTo-CSV
  • ConvertFrom-CSV


Export-FormatData

Saves formatting data from the current session in a formatting file.

Syntax

Export-FormatData -Path <string> [-Force] [-IncludeScriptBlock] [-InputObject <ExtendedTypeDefinition[]>] [-NoClobber] [<CommonParameters>]

Description

The Export-FormatData cmdlet creates Windows PowerShell formatting files (format.ps1xml) from the formatting objects in the current session. It takes the ExtendedTypeDefinition objects that Get-FormatData returns and saves them in a file in XML format.

Windows PowerShell uses the data in formatting files (format.ps1xml) to generate the default display of Microsoft .NET Framework objects in the session. You can view and edit the formatting files and use the Update-FormatData cmdlet to add the formatting data to a session.

For more information about formatting files in Windows PowerShell, see about_Format.ps1xml.

Parameters

-Force

Overwrites an existing output file, even if the file has the read-only attribute.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-IncludeScriptBlock

Determines whether script blocks in the format data are exported.

Because script blocks contain code and can be used maliciously, they are not exported by default.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ExtendedTypeDefinition[]>

Specifies the format data objects to be exported. Enter a variable that contains the objects or a command that gets the objects, such as a Get-FormatData command. You can also pipe the objects from Get-FormatData to Export-FormatData.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-NoClobber

Prevents the cmdlet from overwriting existing files. By default, Export-FormatData overwrites files without warning unless the file has the read-only attribute.

To direct Export-FormatData to overwrite read-only files, use the Force parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies a location for the output file. Enter a path (optional) and file name with a format.ps1xml file name extension. If you omit the path, Export-FormatData creates the file in the current directory.

If you use a file name extension other than .ps1xml, the Update-FormatData cmdlet will not recognize the file.

If you specify an existing file, Export-FormatData overwrites the file without warning, unless the file has the read-only attribute. To overwrite a read-only file, use the Force parameter. To prevent files from being overwritten, use the NoClobber parameter.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.ExtendedTypeDefinition You can pipe ExtendedTypeDefinition objects from Get-FormatData to Export-FormatData.
Outputs | None Export-FormatData does not return any objects. It generates a file and saves it in the specified path.

Notes

To use any formatting file, including an exported formatting file, the execution policy for the session must allow scripts and configuration files to run. For more information, see about_Execution_Policies.

Example 1

C:\PS>get-formatdata -typename * | export-formatdata -path allformat.ps1xml -IncludeScriptBlock

This command exports all of the format data in the session to the AllFormat.ps1xml file.

The command uses the Get-FormatData cmdlet to get the format data in the session. A value of * (all) for the TypeName parameter directs the cmdlet to get all of the data in the session.

The command uses a pipeline operator (|) to send the format data from the Get-FormatData command to the Export-FormatData cmdlet, which exports the format data to the AllFormat.ps1 file.

The Export-FormatData command uses the IncludeScriptBlock parameter to include script blocks in the format data in the file.

Example 2

C:\PS>$f = get-formatdata -typename helpinfoshort

C:\PS> export-formatdata -inputObject $f -path c:\test\help.format.ps1xml -IncludeScriptBlock

Description
-----------
These commands export the format data for the HelpInfoShort type to the Help.format.ps1xml file.

The first command uses the Get-FormatData cmdlet to get the format data for the HelpInfoShort type, and it saves it in the $f variable.

The second command uses the InputObject parameter of the Export-FormatData to enter the format data saved in the $f variable. It also uses the IncludeScriptBlock parameter to include script blocks in the output.

Example 3

C:\PS>get-formatdata -typename System.Diagnostics.Process | export-FormatData -path process.format.ps1xml

C:\PS> Update-FormatData -prependPath .\process.format.ps1xml

C:\PS> get-process p*

Handles  NPM(K)  PM(K)  WS(K) VM(M)   CPU(s)    Id ProcessName
-------  ------  -----  ----- -----   ------    -- -----------
    323                                       5600 powershell
    336                                       3900 powershell_ise
    138                                       4076 PresentationFontCache

Description
-----------
This example shows the effect of omitting the IncludeScriptBlock parameter from an Export-FormatData command.

The first command uses the Get-FormatData cmdlet to get the format data for the System.Diagnostics.Process object that the Get-Process cmdlet returns. The command uses a pipeline operator (|) to send the formatting data to the Export-FormatData cmdlet, which exports it to the Process.format.ps1xml file in the current directory.

In this case, the Export-FormatData command does not use the IncludeScriptBlock parameter.

The second command uses the Update-FormatData cmdlet to add the Process.format.ps1xml file to the current session. The command uses the PrependPath parameter to ensure that the formatting data for process objects in the Process.format.ps1xml file is found before the standard formatting data for process objects.

The third command shows the effects of this change. The command uses the Get-Process cmdlet to get processes that have names that begin with "P". The output shows that property values that are calculated by using script blocks are missing from the display.

See Also

  • Get-FormatData
  • Update-FormatData


Export-ModuleMember

Specifies the module members that are exported.

Syntax

Export-ModuleMember [[-Function] <string[]>] [-Alias <string[]>] [-Cmdlet <string[]>] [-Variable <string[]>] [<CommonParameters>]

Description

The Export-ModuleMember cmdlet specifies the module members (such as cmdlets, functions, variables, and aliases) that are exported from a script module (.psm1) file, or from a dynamic module created by using the New-Module cmdlet. This cmdlet can be used only in a script module file or a dynamic module.

If a script module does not include an Export-ModuleMember command, the functions in the script module are exported, but the variables and aliases are not. When a script module includes an Export-ModuleMember command, only the members specified in the Export-ModuleMember command are exported.

If a script module contains multiple Export-ModuleMember commands, only the members listed in an Export-ModuleMember command are exported.

You can also use Export-ModuleMember to export members that the script module imports from other modules.

Parameters

-Alias <string[]>

Specifies the aliases that are exported from the script module file. Enter the alias names. Wildcards are permitted.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Cmdlet <string[]>

Specifies the cmdlets that are exported from the script module file. Enter the cmdlet names. Wildcards are permitted.

You cannot create cmdlets in a script module file, but you can import cmdlets from a binary module into a script module and re-export them from the script module.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Function <string[]>

Specifies the functions that are exported from the script module file. Enter the function names. Wildcards are permitted. You can also pipe function name strings to Export-ModuleMember.

Required? | false
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | true

-Variable <string[]>

Specifies the variables that are exported from the script module file. Enter the variable names (without a dollar sign). Wildcards are permitted.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe function name strings to Export-ModuleMember.
Outputs | None This cmdlet does not generate any output.

Notes

To exclude a member from the list of exported members, add an Export-ModuleMember command that lists all other members but omits the member that you want to exclude.

Example 1

C:\PS>Export-ModuleMember -function * -alias *

This command exports the aliases defined in the script module, along with the functions defined in the script module.

To export the aliases, which are not exported by default, you must also explicitly specify the functions. Otherwise, only the aliases will be exported.

Example 2

C:\PS>Export-ModuleMember -function Get-Test, New-Test, Start-Test -alias gtt, ntt, stt

This command exports three aliases and three functions defined in the script module.

You can use this command format to specify the names of module members.

Example 3

C:\PS>Export-ModuleMember

This command specifies that no members defined in the script module are exported.

This command prevents the module members from being exported, but it does not hide the members. Users can read and copy module members or use the call operator (&) to invoke module members that are not exported.

Example 4

C:\PS>Export-ModuleMember -variable increment

This command exports only the $increment variable from the script module. No other members are exported.

If you want to export a variable, in addition to exporting the functions in a module, the Export-ModuleMember command must include the names of all of the functions and the name of the variable.

Example 5

C:\PS># From TestModule.psm1

function new-test
    { <function code> }
export-modulemember -function new-test

function validate-test
    { <function code> }

function start-test
    { <function code> }
set-alias stt start-test
export-modulemember -function *-test -alias stt

These commands show how multiple Export-ModuleMember commands are interpreted in a script module (.psm1) file.

These commands create three functions and one alias, and then they export two of the functions and the alias.

Without the Export-ModuleMember commands, all three of the functions would be exported, but the alias would not be exported. With the Export-ModuleMember commands, only the Get-Test and Start-Test functions and the STT alias are exported.

Example 6

C:\PS>new-module -script {function SayHello {"Hello!"}; set-alias Hi SayHello; Export-ModuleMember -alias Hi -function SayHello}

This command shows how to use Export-ModuleMember in a dynamic module that is created by using the New-Module cmdlet.

In this example, Export-ModuleMember is used to export both the "Hi" alias and the "SayHello" function in the dynamic module.

Example 7

C:\PS>function export
{
    param (
        [parameter(mandatory=$true)] [validateset("function","variable")] $type,
        [parameter(mandatory=$true)] $name,
        [parameter(mandatory=$true)] $value
    )
    if ($type -eq "function")
    {
        Set-item "function:script:$name" $value
        Export-ModuleMember $name
    }
    else
    {
        Set-Variable -scope Script $name $value
        Export-ModuleMember -variable $name
    }
}

export function New-Test
{
  ...
}

function helper
{
  ...
}

export variable interval 0
$interval = 2

Description
-----------
This example includes a function named Export that declares a function or creates a variable, and then writes an Export-ModuleMember command for the function or variable. This lets you declare and export a function or variable in a single command.

To use the Export function, include it in your script module. To export a function, type "Export" before the Function keyword.

To export a variable, use the following format to declare the variable and set its value:

    export variable <variable-name> <value>

The commands in the example show the correct format. In this example, only the New-Test function and the $Interval variable are exported.

See Also

  • Import-Module
  • Get-Module
  • Remove-Module
  • about_Modules


Export-PSSession

Imports commands from another session and saves them in a Windows PowerShell module.

Syntax

Export-PSSession [-Session] <PSSession> [-OutputModule] <string> [[-CommandName] <string[]>] [[-FormatTypeName] <string[]>] [-AllowClobber] [-ArgumentList <Object[]>] [-CommandType {<Alias> | <Function> | <Filter> | <Cmdlet> | <ExternalScript> | <Application> | <Script> | <All>}] [-Encoding <string>] [-Force] [-Module <string[]>] [<CommonParameters>]

Description

The Export-PSSession cmdlet gets cmdlets, functions, aliases, and other command types from another PSSession on a local or remote computer and saves them in a Windows PowerShell module. To add the commands from the module to the current session, use the Import-Module cmdlet.

Unlike Import-PSSession, which imports commands from another PSSession into the current session, Export-PSSession saves the commands in a module. The commands are not imported into the current session.

To export commands, first use the New-PSSession cmdlet to create a PSSession that has the commands that you want to export. Then use the Export-PSSession cmdlet to export the commands. By default, Export-PSSession exports all commands, except for commands that exist in the current session, but you can use the CommandName parameters to specify the commands to export.

The Export-PSSession cmdlet uses the implicit remoting feature of Windows PowerShell. When you import commands into the current session, they run implicitly in the original session or in a similar session on the originating computer.

Parameters

-AllowClobber

Exports the specified commands, even if they have the same names as commands in the current session.

If you import a command with the same name as a command in the current session, the imported command hides or replaces the original commands. For more information, see about_Command_Precedence.

Export-PSSession does not import commands that have the same names as commands in the current session. The default behavior is designed to prevent command name conflicts.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ArgumentList <Object[]>

Exports the variant of the command that results from using the specified arguments (parameter values).

For example, to export the variant of the Get-Item command in the certificate (Cert:) drive in the PSSession in $s, type "export-pssession -session $s -command Get-Item -argumentlist cert:".

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CommandName <string[]>

Exports only the commands with the specified names or name patterns. Wildcards are permitted. Use "CommandName" or its alias, "Name".

By default, Export-PSSession exports all commands from the PSSession except for commands that have the same names as commands in the current session. This prevents imported commands from hiding or replacing commands in the current session. To export all commands, even those that hide or replace other commands, use the AllowClobber parameter.

If you use the CommandName parameter, the formatting files for the commands are not exported unless you use the FormatTypeName parameter. Similarly, if you use the FormatTypeName parameter, no commands are exported unless you use the CommandName parameter.

Required? | false
Position? | 3
Default Value | All commands in the session.
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-CommandType <CommandTypes>

Exports only the specified types of command objects. Use "CommandType" or its alias, "Type".

Valid values are:

-- Alias: All Windows PowerShell aliases in the current session.

-- All: All command types. It is the equivalent of "Get-Command *".

-- Application: All files other than Windows PowerShell files in paths listed in the Path environment variable ($env:path), including .txt, .exe, and .dll files.

-- Cmdlet: The cmdlets in the current session. "Cmdlet" is the default.

-- ExternalScript: All .ps1 files in the paths listed in the Path environment variable ($env:path).

-- Filter and Function: All Windows PowerShell functions.

-- Script: Script blocks in the current session.

Required? | false
Position? | named
Default Value | All commands in the session.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Encoding <string>

Specifies the encoding for the output files. Valid values are "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", and "OEM". The default is "UTF-8".

Required? | false
Position? | named
Default Value | UTF-8
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Overwrites one or more existing output files, even if the file has the read-only attribute.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FormatTypeName <string[]>

Exports formatting instructions only for the specified Microsoft .NET Framework types. Enter the type names. By default, Export-PSSession exports formatting instructions for all .NET Framework types that are not in the System.Management.Automation namespace.

The value of this parameter must be the name of a type that is returned by a Get-FormatData command in the session from which the commands are being imported. To get all of the formatting data in the remote session, type *.

If you use the FormatTypeName parameter, no commands are exported unless you use the CommandName parameter.

Similarly, if you use the CommandName parameter, the formatting files for the commands are not exported unless you use the FormatTypeName parameter.

Required? | false
Position? | 4
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Module <string[]>

Exports only the commands in the specified Windows PowerShell snap-ins and modules. Enter the snap-in and module names. Wildcards are not permitted.

For more information, see about_PSSnapins and Import-Module.

Required? | false
Position? | named
Default Value | All commands in the session.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OutputModule <string>

Specifies a path (optional) and name for the module that Export-PSSession creates. The default path is $home\Documents\WindowsPowerShell\Modules. This parameter is required.

If the module subdirectory or any of the files that Export-PSSession creates already exist, the command fails. To overwrite existing files, use the Force parameter.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Session <PSSession>

Specifies the PSSession from which the commands are exported. Enter a variable that contains a session object or a command that gets a session object, such as a Get-PSSession command. This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Export-PSSession.
Outputs | System.IO.FileInfo Export-PSSession returns a list of files that comprise the module that it created.

Notes

Export-PSSession relies on the Windows PowerShell remoting infrastructure. To use this cmdlet, the computer must be configured for remoting. For more information, see about_Remote_Requirements.

You cannot use Export-PSSession to export a Windows PowerShell provider.

Exported commands run implicitly in the PSSession from which they were exported. However, the details of running the commands remotely are handled entirely by Windows PowerShell. You can run the exported commands just as you would run local commands.

Export-Module captures and saves information about the PSSession in the module that it exports. If the PSSession from which the commands were exported is closed when you import the module, and there are no active PSSessions to the same computer, the commands in the module attempt to re-create the PSSession. If attempts to re-create the PSSession fail, the exported commands will not run.

The session information that Export-Module captures and saves in the module does not include session options, such as those that you specify in the $PSSessionOption automatic variable or by using the SessionOption parameters of the New-PSSession, Enter-PSSession, or Invoke-Command cmdlet. If the original PSSession is closed when you import the module, the module will use another PSSession to the same computer, if one is available. To enable the imported commands to run in a correctly configured session, create a PSSession with the options that you want before you import the module.

To find the commands to export, Export-PSSession uses the Invoke-Command cmdlet to run a Get-Command command in the PSSession. To get and save formatting data for the commands, it uses the Get-FormatData and Export-FormatData cmdlets. You might see error messages from Invoke-Command, Get-Command, Get-FormatData, and Export-FormatData when you run an Export-PSSession command. Also, Export-PSSession cannot export commands from a session that does not include the Get-Command, Get-FormatData, Select-Object, and Get-Help cmdlets.

Export-PSSession uses the Write-Progress cmdlet to display the progress of the command. You might see the progress bar while the command is running.

Exported commands have the same limitations as other remote commands, including the inability to start a program with a user interface, such as Notepad.

Because Windows PowerShell profiles are not run in PSSessions, the commands that a profile adds to a session are not available to Export-PSSession. To export commands from a profile, use an Invoke-Command command to run the profile in the PSSession manually before exporting commands.

The module that Export-PSSession creates might include a formatting file, even if the command does not import formatting data. If the command does not import formatting data, any formatting files that are created will not contain formatting data.

Example 1

C:\PS>$s = new-pssession -computerName Server01

C:\PS> export-pssession -session $s -outputModule Server01

The commands in this example export all commands from a PSSession on the Server01 computer to the Server01 module on the local computer except for commands that have the same names as commands in the current session. It also exports the formatting data for the commands.

The first command creates a PSSession on the Server01 computer. The second command exports the commands and formatting data from the session into the Server01 module.

Example 2

C:\PS>$s = new-pssession -ConnectionUri http://exchange.microsoft.com/mailbox -credential exchangeadmin01@hotmail.com -authentication negotiate

C:\PS> export-pssession -session $r -module exch* -commandname get-*, set-* -formattypename * -outputModule $pshome\Modules\Exchange -encoding ASCII

These commands export the Get and Set commands from a Microsoft Exchange Server snap-in on a remote computer to an Exchange module in the $pshome\Modules directory on the local computer.

Placing the module in the $pshome\Module directory makes it accessible to all users of the computer.

Example 3

C:\PS>$s = new-pssession -computerName Server01 -credential Server01\User01

C:\PS> export-pssession -session $s -outputModule TestCmdlets -type cmdlet -commandname *test* -formattypename *

C:\PS> remove-pssession $s

C:\PS> import-module TestCmdlets

C:\PS> get-help test*

C:\PS> test-files

These commands export cmdlets from a PSSession on a remote computer and save them in a module on the local computer. Then, the commands add the cmdlets from the module to the current session so that they can be used.

The first command creates a PSSession on the Server01 computer and saves it in the $s variable.

The second command exports the cmdlets whose names begin with "Test" from the PSSession in $s to the TestCmdlets module on the local computer.

The third command uses the Remove-PSSession cmdlet to delete the PSSession in $s from the current session. This command shows that the PSSession need not be active to use the commands that were imported from it.

The fourth command, which can be run in any session at any time, uses the Import-Module cmdlet to add the cmdlets in the TestCmdlets module to the current session.

The fifth command uses the Get-Help cmdlet to get help for cmdlets whose names begin with "Test." After the commands in a module are added to the current session, you can use the Get-Help and Get-Command cmdlets to learn about the imported commands, just as you would use them for any command in the session.

The sixth command uses the Test-Files cmdlet, which was exported from the Server01 computer and added to the session.

Although it is not evident, the Test-Files command actually runs in a remote session on the computer from which the command was imported. Windows PowerShell creates a session from information that is stored in the module.

Example 4

C:\PS>export-pssession -session $s -AllowClobber -outputModule AllCommands

This command exports all commands and all formatting data from the PSSession in the $s variable into the current session. The command uses the AllowClobber parameter to include commands with the same names as commands in the current session.

Example 5

C:\PS>$options = New-PSSessionOption -NoMachineProfile

C:\PS> $s = new-pssession -computername Server01 -sessionoption $options

C:\PS> export-pssession -session $s -outputModule Server01

C:\PS> remove-pssession $s

C:\PS> new-pssession -computername Server01 -sessionoption $options

C:\PS> import-module Server01

This example shows how to run the exported commands in a session with particular options when the PSSession from which the commands were exported is closed.

When you use Export-PSSession, it saves information about the original PSSession in the module that it creates. When you import the module, if the original remote session is closed, the module will use any open remote session that connects to originating computer.

If the current session does not include a remote session to the originating computer, the commands in the module will re-establish a session to that computer. However, Export-PSSession does not save special options, such as those set by using the SessionOption parameter of New-PSSession, in the module.

Therefore, if you want to run the exported commands in a remote session with particular options, you need to create a remote session with the options that you want before you import the module.

The first command uses the New-PSSessionOption cmdlet to create a PSSessionOption object, and it saves the object in the $options variable.

The second command creates a PSSession that includes the specified options. The command uses the New-PSSession cmdlet to create a PSSession on the Server01 computer. It uses the SessionOption parameter to submit the option object in $options.

The third command uses the Export-PSSession cmdlet to export commands from the PSSession in $s to the Server01 module.

The fourth command uses the Remove-PSSession cmdlet to delete the PSSession in the $s variable.

The fifth command uses the New-PSSession cmdlet to create a new PSSession that connects to the Server01 computer. This PSSession also uses the session options in the $options variable.

The sixth command uses the Import-Module cmdlet to import the commands from the Server01 module. The commands in the module run in the PSSession on the Server01 computer.

See Also

  • about_Command_Precedence
  • Import-PSSession
  • New-PSSession
  • Import-Module
  • Invoke-Command
  • about_PSSessions


ForEach-Object

Performs an operation against each of a set of input objects.

Syntax

ForEach-Object [-Process] <ScriptBlock[]> [-Begin <scriptblock>] [-End <scriptblock>] [-InputObject <psobject>] [<CommonParameters>]

Description

The ForEach-Object cmdlet performs an operation on each of a set of input objects. The input objects can be piped to the cmdlet or specified by using the InputObject parameter.

The operation to perform is described within a script block that is provided to the cmdlet as the value of the Process parameter. The script block can contain any Windows PowerShell script.

Within the script block, the current input object is represented by the $_ variable.

In addition to using the script block that describes the operations to be carried out on each input object, you can provide two additional script blocks. One, specified as the value of the Begin parameter, runs before the first input object is processed. The other, specified as the value of the End parameter, runs after the last input object is processed.

The results of the evaluation of all the script blocks, including the ones specified with Begin and End, are passed down the pipeline.

Parameters

-Begin <scriptblock>

Specifies a script block to run before processing any input objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-End <scriptblock>

Specifies a script block to run after processing all input objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Accepts an object that the script block specified in the process parameter will act upon. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Process <ScriptBlock[]>

Specifies the script block that is applied to each incoming object.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to ForEach-Object.
Outputs | System.Management.Automation.PSObject The objects that ForEach-Object returns are determined by the input.

Example 1

C:\PS>30000,56798,12432 | foreach-object -process {$_/1024}

This command accepts an array of integers, divides each one of them by 1024, and displays the results.

Example 2

C:\PS>get-childitem C:\ | foreach-object -process { $_.length / 1024 }

This command retrieves the files and directories in the root of the C: drive, and it returns and displays the size of each of them. The zeros represent directories in which no file size was available.

Example 3

C:\PS>$events = get-eventlog -logname system -newest 1000

C:\PS> $events | foreach-object -begin {get-date} -process {out-file -filepath events.txt -append -inputobject $_.message} -end {get-date}

This command retrieves the 1000 most recent events from the system log and stores them in the $events variable. It then pipes the events to the ForEach-Object cmdlet. The Begin parameter displays the current date and time. Next, the Process parameter uses the Out-File cmdlet to create a text file named events.txt and stores the message property of each of the events in that file. Last, the End parameter is used to display the date and time after all of the processing has completed.

Example 4

C:\PS>get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemproperty -path $_.pspath -name RemotePath -value $_.RemotePath.ToUpper();}

This command changes the value of the RemotePath registry entry in all of the subkeys under the HKCU:\Network key to uppercase text. You can use this format to change the form or content of a registry entry value.

Each subkey in the Network key represents a mapped network drive that will reconnect at logon. The RemotePath entry contains the UNC path of the connected drive. For example, if you map the E: drive to \\Server\Share, there will be an E subkey of HKCU:\Network and the value of the RemotePath registry entry in the E subkey will be \\Server\Share.

The command uses the Get-ItemProperty cmdlet to get all of the subkeys of the Network key and the Set-ItemProperty cmdlet to change the value of the RemotePath registry entry in each key. In the Set-ItemProperty command, the path is the value of the PSPath property of the registry key. (This is a property of the Microsoft .NET Framework object that represents the registry key; it is not a registry entry.) The command uses the ToUpper() method of the RemotePath value, which is a string (REG_SZ).

Because Set-ItemProperty is changing the property of each key, the ForEach-Object cmdlet is required to access the property.


Format-Custom

Uses a customized view to format the output.

Syntax

Format-Custom [[-Property] <Object[]>] [-Depth <int>] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-InputObject <psobject>] [-ShowError] [-View <string>] [<CommonParameters>]

Description

The Format-Custom cmdlet formats the output of a command as defined in an alternate view. Format-Custom is designed to display views that are not just tables or just lists. You can use the views defined in the *format.PS1XML files in the Windows PowerShell directory, or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to add them to Windows PowerShell.

Parameters

-Depth <int>

Specifies the number of columns in the display.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DisplayError

Displays errors at the command line.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Expand <string>

Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the ICollection (System.Collections) interface. The default value is EnumOnly.

Valid values are:

-- EnumOnly: Displays the properties of the objects in the collection.

-- CoreOnly: Displays the properties of the collection object.

-- Both: Displays the properties of the collection object and the properties of objects in the collection.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Directs the cmdlet to display all of the error information. Use with the DisplayError or ShowError parameters. By default, when an error object is written to the error or display streams, only some of the error information is displayed.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-GroupBy <Object>

Formats the output in groups based on a shared property or value. Enter an expression or a property of the output.

The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Name (or Label) <string>

-- Expression <string> or <script block>

-- FormatString <string>

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be formatted. Enter a variable that contains the objects or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Property <Object[]>

Specifies the object properties that appear in the display and the order in which they appear. Wildcards are permitted.

If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command.

The value of the Property parameter can be a new calculated property. To create a calculated property, use a hash table. Valid keys are:

-- Expression <string> or <script block>

-- Depth <int32>

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ShowError

Sends errors through the pipeline.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-View <string>

Specifies the name of an alternate format or "view." If you omit this parameter, Format-Custom uses a default custom view. You cannot use the Property and View parameters in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Format-Custom
Outputs | Microsoft.PowerShell.Commands.Internal.Format Format-Custom returns the format objects that represent the display.

Notes

Format-Custom is designed to display views that are not just tables or just lists. To display an alternate table view, use Format-Table. To display an alternate list view, use Format-List.

You can also refer to Format-Custom by its built-in alias, "fc". For more information, see about_Aliases.

The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them.

Example 1

C:\PS>get-command start-transcript | format-custom -view MyView

This command formats information about the Start-Transcript cmdlet in the format defined by the MyView view, a custom view created by the user. To run this command successfully, you must first create a new PS1XML file, define the MyView view, and then use the Update-FormatData command to add the PS1XML file to Windows PowerShell.

Example 2

C:\PS>get-process Winlogon | format-custom

This command formats information about the Winlogon process in an alternate customized view. Because the command does not use the View parameter, Format-Custom uses a default custom view to format the data.


Format-List

Formats the output as a list of properties in which each property appears on a new line.

Syntax

Format-List [[-Property] <Object[]>] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-InputObject <psobject>] [-ShowError] [-View <string>] [<CommonParameters>]

Description

The Format-List cmdlet formats the output of a command as a list of properties in which each property is displayed on a separate line. You can use Format-List to format and display all or selected properties of an object as a list (format-list *).

Because more space is available for each item in a list than in a table, Windows PowerShell displays more properties of the object in the list, and the property values are less likely to be truncated.

Parameters

-DisplayError

Displays errors at the command line.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Expand <string>

Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the ICollection (System.Collections) interface. The default value is EnumOnly.

Valid values are:

-- EnumOnly: Displays the properties of the objects in the collection.

-- CoreOnly: Displays the properties of the collection object.

-- Both: Displays the properties of the collection object and the properties of objects in the collection.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Directs the cmdlet to display all of the error information. Use with the DisplayError or ShowError parameters. By default, when an error object is written to the error or display streams, only some of the error information is displayed.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-GroupBy <Object>

Formats the output in groups based on a shared property or value. Enter an expression or a property of the output.

The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Name (or Label) <string>

-- Expression <string> or <script block>

-- FormatString <string>

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be formatted. Enter a variable that contains the objects or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Property <Object[]>

Specifies the object properties that appear in the display and the order in which they appear. Wildcards are permitted.

If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command.

The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Name (or Label) <string>

-- Expression <string> or <script block>

-- FormatString <string>

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ShowError

Sends errors through the pipeline.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-View <string>

Specifies the name of an alternate list format or "view." You cannot use the Property and View parameters in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Format-List.
Outputs | Microsoft.PowerShell.Commands.Internal.Format Format-List returns the format objects that represent the list.

Notes

You can also refer to Format-List by its built-in alias, "FL". For more information, see about_Aliases.

The format cmdlets, such as Format-List, arrange the data to be displayed but do not display it. The data is displayed by the output features of Windows PowerShell and by the cmdlets that contain the Out verb (the Out cmdlets), such as Out-Host, Out-File, and Out-Printer.

If you do not use a format cmdlet, Windows PowerShell applies that default format for each object that it displays.

The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them.

The View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Windows PowerShell directory, or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows PowerShell.

The alternate view for the View parameter must use the list format; if not, the command fails. If the alternate view is a table, use Format-Table. If the alternate view is neither a list nor a table, use Format-Custom.

Example 1

C:\PS>get-service | format-list

This command formats information about services on the computer as a list. By default, the services are formatted as a table. The Get-Service cmdlet gets objects representing the services on the computer. The pipeline operator (|) passes the results through the pipeline to Format-List. Then, the Format-List command formats the service information in a list and sends it to the default output cmdlet for display.

Example 2

C:\PS>$a = get-childitem $pshome\*.ps1xml

These commands display information about the PS1XML files in the Windows PowerShell directory as a list. The first command gets the objects representing the files and stores them in the $a variable. The second command uses Format-List to format information about objects stored in $a. This command uses the InputObject parameter to pass the variable to Format-List, which then sends the formatted output to the default output cmdlet for display.

Example 3

C:\PS>get-process | format-list -property name, basepriority, priorityclass

This command displays the name, base priority, and priority class of each process on the computer. It uses the Get-Process cmdlet to get an object representing each process. The pipeline operator (|) passes the process objects through the pipeline to Format-List. Format-List formats the processes as a list of the specified properties. The "Property" parameter name is optional, so you can omit it.

Example 4

C:\PS>get-process winlogon | format-list -property *

This command displays all of the properties of the Winlogon process. It uses the Get-Process cmdlet to get an object representing the Winlogon process. The pipeline operator (|) passes the Winlogon process object through the pipeline to Format-List. The command uses the Property parameter to specify the properties and the * to indicate all properties. Because the name of the Property parameter is optional, you can omit it and type the command as: "format-list *". Format-List automatically sends the results to the default output cmdlet for display.


Format-Table

Formats the output as a table.

Syntax

Format-Table [[-Property] <Object[]>] [-AutoSize] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-HideTableHeaders] [-InputObject <psobject>] [-ShowError] [-View <string>] [-Wrap] [<CommonParameters>]

Description

The Format-Table cmdlet formats the output of a command as a table with the selected properties of the object in each column. The object type determines the default layout and properties that are displayed in each column, but you can use the Property parameter to select the properties that you want to see.

You can also use a hash table to add calculated properties to an object before displaying it and to specify the column headings in the table. To add a calculated property, use the Property or GroupBy parameters.

Parameters

-AutoSize

Adjusts the column size and number of columns based on the width of the data. By default, the column size and number are determined by the view.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DisplayError

Displays errors at the command line.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Expand <string>

Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the ICollection (System.Collections) interface. The default value is EnumOnly.

Valid values are:

-- EnumOnly: Displays the properties of the objects in the collection.

-- CoreOnly: Displays the properties of the collection object.

-- Both: Displays the properties of the collection object and the properties of objects in the collection.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Directs the cmdlet to display all of the error information. Use with the DisplayError or ShowError parameters. By default, when an error object is written to the error or display streams, only some of the error information is displayed.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-GroupBy <Object>

Arranges sorted output in separate tables based on a property value. For example, you can use GroupBy to list services in separate tables based on their status.

Enter an expression or a property of the output. The output must be sorted before you send it to Format-Table.

The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Name (or Label) <string>

-- Expression <string> or <script block>

-- FormatString <string>

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-HideTableHeaders

Omits the column headings from the table.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be formatted. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Property <Object[]>

Specifies the object properties that appear in the display and the order in which they appear. Type one or more property names (separated by commas), or use a hash table to display a calculated property. Wildcards are permitted.

If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command.

The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Name (or Label) <string>

-- Expression <string> or <script block>

-- FormatString <string>

-- Width <int32>

-- Alignment (value can be "Left", "Center", or "Right")

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ShowError

Sends errors through the pipeline.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-View <string>

Specifies the name of an alternate table format or "view." You cannot use the Property and View parameters in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Wrap

Displays text that exceeds the column width on the next line. By default, text that exceeds the column width is truncated.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Format-Table.
Outputs | Microsoft.PowerShell.Commands.Internal.Format Format-Table returns format objects that represent the table.

Notes

You can also refer to Format-Table by its built-in alias, "FT". For more information, see about_Aliases.

The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them.

The View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Windows PowerShell directory or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows PowerShell.

The alternate view for the View parameter must use table format; if it does not, the command fails. If the alternate view is a list, use Format-List. If the alternate view is neither a list nor a table, use Format-Custom.

Example 1

C:\PS>get-pssnapin | format-table -auto

This command formats information about Windows PowerShell snap-ins in a table. By default, they are formatted in a list. The Get-PSSnapin cmdlets gets objects representing the snap-ins. The pipeline operator (|) passes the object to the Format-Table command. Format-Table formats the objects in a table. The Autosize parameter adjusts the column widths to minimize truncation.

Example 2

C:\PS>get-process | sort-object -property basepriority | format-table -groupby basepriority -wrap

This command displays the processes on the computer in groups with the same base priority.

The Get-Process cmdlet gets objects representing each process on the computer. The pipeline operator (|) passes the object to the Sort-Object cmdlet, which sorts the objects in order of their base priority.

Another pipeline operator passes the results to the Format-Table command. The GroupBy parameter arranges the data about the processes into groups based on the value of their BasePriority property. The Wrap parameter ensures that data is not truncated.

Example 3

C:\PS>get-process | sort-object starttime | format-table -view starttime

This command displays information about the processes on the computer in group based on the start date of the process. It uses the Get-Process cmdlet to get objects representing the processes on the computer. The pipeline operator (|) sends the output of Get-Process to the Sort-Object cmdlet, which sorts it based on the StartTime property. Another pipeline operator sends the sorted results to Format-Table.

The View parameter is used to select the StartTime view that is defined in the DotNetTypes.format.ps1xml formatting file for System.Diagnostics.Process objects, such as those returned by Get-Process. This view converts the StartTime of the process to a short date and then groups the processes by start date.

The DotNetTypes.format.ps1xml formatting file also contains a Priority view for processes, and you can create your own format.ps1xml files with customized views.

Example 4

C:\PS>get-service | format-table -property Name, DependentServices

This command displays all of the services on the computer in a table with two columns, Name and DependentServices. The command uses the Get-Service cmdlet to get all of the services on the computer. The pipeline operator (|) sends the results to the Format-Table cmdlet, which formats the output in a table. The Property parameter specifies the properties that appear in the table as columns. The name of the Property parameter is optional, so you can omit it ("format-table name, dependentservices").

Property and DependentServices are just two of the properties of service objects. To view all of the properties, type "get-service | get-member".

Example 5

C:\PS>get-process notepad | format-table ProcessName, `
@{Label="TotalRunningTime"; Expression={(get-date) - $_.StartTime}}

This command shows how to use a calculated property in a table. The command displays a table with the process name and total running time of all Notepad processes on the local computer. The total running time is calculated by subtracting the start time of each process from the current time.

The command uses the Get-Process cmdlet to get all processes named "Notepad" on the local computer. The pipeline operator (|) sends the results to Format-Table, which displays a table with two columns: ProcessName, a standard property of processes, and TotalRunningTime, a calculated property.

The TotalRunningTime property is specified by a hash table with two keys, Label and Expression. The name of the property is assigned to the Label key. The calculation is assigned to the Expression key. The expression gets the StartTime property of each process object and subtracts it from the result of a Get-Date command, which gets the current date (and time).

Example 6

C:\PS>$processes = get-wmiobject -ComputerName Server01 win32_process -filter "name='notepad.exe'"

C:\PS> $processes | format-table ProcessName, @{ Label = "Total  Running Time"; `
Expression={(get-date) - $_.ConvertToDateTime($_.CreationDate)}}

These commands are similar to the previous command, except that these commands use the Get-WmiObject cmdlet and the Win32_Process class to display information about Notepad processes on a remote computer.

The first command uses the Get-WmiObject cmdlet to get instances of the Windows Management Instrumentation (WMI) Win32_Process class that describes all of the processes on the Server01 computer that are named Notepad.exe. The command stores the process information in the $processes variable.

The second command uses a pipeline operator (|) to send the process information in the $processes variable to the Format-Table cmdlet, which displays the ProcessName of each process along with a new calculated property.

The command assigns the name of the new calculated property, Total Running Time, to the Label key. The script block that is assigned to the Expression key calculates how long the process has been running by subtracting the creation date of the process from the current date. The Get-Date cmdlet gets the current date. The ConvertToDateTime method converts the CreationDate property of the Win32_Process object from a WMI CIM_DATETIME object to a Microsoft .NET Framework DateTime object that can be compared with the output of Get-Date. Then, the converted creation date is subtracted from the current date. The result is the value of Total Running Time.

The backtick characters (`) are line continuation characters.

See Also

  • Format-List
  • Format-Wide
  • Format-Custom


Format-Wide

Formats objects as a wide table that displays only one property of each object.

Syntax

Format-Wide [[-Property] <Object>] [-AutoSize] [-Column <int>] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-InputObject <psobject>] [-ShowError] [-View <string>] [<CommonParameters>]

Description

The Format-Wide cmdlet formats objects as a wide table that displays only one property of each object. You can use the Property parameter to determine which property is displayed.

Parameters

-AutoSize

Adjusts the column size and number of columns based on the width of the data. By default, the column size and number are determined by the view. You cannot use the AutoSize and Column parameters in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Column <int>

Specifies the number of columns in the display. You cannot use the AutoSize and Column parameters in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DisplayError

Displays errors at the command line.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Expand <string>

Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the ICollection (System.Collections) interface. The default value is EnumOnly.

Valid values are:

-- EnumOnly: Displays the properties of the objects in the collection.

-- CoreOnly: Displays the properties of the collection object.

-- Both: Displays the properties of the collection object and the properties of objects in the collection.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Overrides restrictions that prevent the command from succeeding, just so the changes do not compromise security. For example, Force will override the read-only attribute or create directories to complete a file path, but it will not attempt to change file permissions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-GroupBy <Object>

Formats the output in groups based on a shared property or value. Enter an expression or a property of the output.

The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Name (or Label) <string>

-- Expression <string> or <script block>

-- FormatString <string>

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be formatted. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Property <Object>

Specifies the object properties that appear in the display and the order in which they appear. Wildcards are permitted.

If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command.

The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Expression <string> or <script block>

-- FormatString <string>

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ShowError

Sends errors through the pipeline.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-View <string>

Specifies the name of an alternate table format or "view." You cannot use the Property and View parameters in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Format-Wide.
Outputs | Microsoft.PowerShell.Commands.Internal.Format Format-Wide returns format objects that represent the table.

Notes

You can also refer to Format-Wide by its built-in alias, "fw". For more information, see about_Aliases.

The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them.

The -View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Windows PowerShell directory or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows PowerShell.

The alternate view for the View parameter must use table format; if it does not, the command fails. If the alternate view is a list, use Format-List. If the alternate view is neither a list nor a table, use Format-Custom.

Example 1

C:\PS>get-childitem | format-wide -column 3

This command displays the names of files in the current directory in three columns across the screen. The Get-ChildItem cmdlet gets objects representing each file in the directory. The pipeline operator (|) passes the file objects through the pipeline to Format-Wide, which formats them for output. The Column parameter specifies the number of columns.

Example 2

C:\PS>get-childitem HKCU:\software\microsoft | format-wide -property pschildname -autosize

This command displays the names of registry keys in the HKEY_CURRENT_USER\Software\Microsoft key. The Get-ChildItem cmdlet gets objects representing the keys. The path is specified as "HKCU:", one of the drives exposed by the Windows PowerShell Registry provider, followed by the key path. The pipeline operator (|) passes the registry key objects through the pipeline to Format-Wide, which formats them for output. The Property parameter specifies the name of the property, and the AutoSize parameter adjusts the columns for readability.


Get-Acl

Gets the security descriptor for a resource, such as a file or registry key.

Syntax

Get-Acl [[-Path] <string[]>] [-Audit] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-UseTransaction] [<CommonParameters>]

Description

The Get-Acl cmdlet gets objects that represent the security descriptor of a file or resource. The security descriptor contains the access control lists (ACLs) of the resource. The ACL specifies the permissions that users and user groups have to access the resource.

Parameters

-Audit

Gets the audit data for the security descriptor from the system access control list (SACL).

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Retrieves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to a resource. Get-Acl gets the security descriptor of the resource indicated by the path. Wildcards are permitted. If you omit the Path parameter, Get-Acl gets the security descriptor of the current directory.

The parameter name ("Path") is optional.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Get-Acl.
Outputs | System.Security.AccessControl Get-Acl returns an object that represents the ACLs that it gets. The object type depends upon the ACL type.

Notes

By default, Get-Acl displays the Windows PowerShell path to the resource (<provider>::<resource-path>), the owner of the resource, and "Access", a list (array) of the access control entries in the discretionary access control list (DACL) for the resource. The DACL list is controlled by the resource owner.

When you format the result as a list, ("get-acl | Format-List"), in addition to the path, owner, and access list, Windows PowerShell displays the following fields:

-- Group: The security group of the owner.

-- Audit: A list (array) of entries in the system access control list (SACL). The SACL specifies the types of access attempts for which Windows generates audit records.

-- Sddl: The security descriptor of the resource displayed in a single text string in Security Descriptor Definition Language format. Windows PowerShell uses the GetSddlForm method of security descriptors to retrieve this data.

Because Get-Acl is supported by the file system and registry providers, you can use Get-Acl to view the ACL of file system objects, such as files and directories, and registry objects, such as registry keys and entries.

Example 1

C:\PS>get-acl C:\windows

This command gets the security descriptor of the C:Windows directory.

Example 2

C:\PS>get-acl C:\Windows\k*.log | format-list -property PSPath, Sddl

This command gets the Windows PowerShell path and SDDL for all of the .log files in the C:\Windows directory whose names begin with "k."

The command uses Get-Acl to get objects representing the security descriptors of each log file. It uses a pipeline operator (|) to send the results to the Format-List cmdlet. The command uses the Property parameter of Format-List to display only the PsPath and SDDL properties of each security descriptor object.

Lists are often used in Windows PowerShell, because long values appear truncated in tables.

The SDDL values are valuable to system administrators, because they are simple text strings that contain all of the information in the security descriptor. As such, they are easy to pass and store, and they can be parsed when needed.

Example 3

C:\PS>get-ACL c:/windows/k*.log -Audit | foreach-object { $_.Audit.Count }

This command gets the security descriptors of the .log files in the C:\Windows directory whose names begin with "k." It uses the Audit parameter to retrieve the audit records from the SACL in the security descriptor. Then it uses the For-EachObject parameter to count the number of audit records associated with each file. The result is a list of numbers representing the number of audit records for each log file.

Example 4

C:\PS>get-acl -path hklm:\system\currentcontrolset\control | format-list

This command uses Get-Acl to get the security descriptor of the Control subkey (HKLM\SYSTEM\CurrentControlSet\Control) of the registry.

The Path parameter specifies the Control subkey. The pipeline operator (|) passes the security descriptor that Get-Acl retrieves to the Format-List command, which formats the properties of the security descriptor as a list so that they are easy to read.

See Also

  • Set-Acl


Get-Alias

Gets the aliases for the current session.

Syntax

Get-Alias [[-Name] <string[]>] [-Exclude <string[]>] [-Scope <string>] [<CommonParameters>]

Get-Alias [-Definition <string[]>] [-Exclude <string[]>] [-Scope <string>] [<CommonParameters>]

Description

The Get-Alias cmdlet gets the aliases (alternate names for commands and executable files) in the current session. This includes built-in aliases, aliases that you have set or imported, and aliases that you have added to your Windows PowerShell profile.

By default, Get-Alias takes an alias and returns the command name. When you use the Definition parameter, Get-Alias takes a command name and returns its aliases.

Parameters

-Definition <string[]>

Gets the aliases for the specified item. Enter the name of a cmdlet, function, script, file, or executable file.

This parameter is called Definition, because it searches for the item name in the Definition property of the alias object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Name and Definition parameters. Enter a name, a definition, or a pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the aliases to retrieve. Wildcards are permitted. By default, Get-Alias retrieves all aliases defined for the current session. The parameter name ("Name") is optional. You can also pipe alias names to Get-Alias.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Scope <string>

Gets only the aliases in the specified scope. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe alias names to Get-Alias.
Outputs | System.Management.Automation.AliasInfo Get-Alias returns an object that represents each alias.

Notes

An alias is an alternate name or nickname for a cmdlet, function, or an executable file. To run the cmdlet, function, or executable, you can use its full name or any alias. For more information, see about_Aliases.

To create a new alias, use Set-Alias or New-Alias. To delete an alias, use Remove-Item.

Example 1

C:\PS>get-alias

This command gets all aliases in the current session.

Example 2

C:\PS>get-alias -name g*, s* -exclude get-*

This command gets all aliases that begin with "g" or "s", except for aliases that begin with "get-".

Example 3

C:\PS>get-alias -definition Get-ChildItem

This command gets the aliases for the Get-ChildItem cmdlet.

By default, the Get-Alias cmdlet gets the item name when you know the alias. The Definition parameter gets the alias when you know the item name.

Example 4

C:\PS>get-alias | where-object {$_.Options -match "ReadOnly"}

This command retrieves all aliases in which the value of the Options property is ReadOnly. This command provides a quick way to find the aliases that are built into Windows PowerShell, because they have the ReadOnly option.

Options is just one property of the AliasInfo objects that Get-Alias gets. To find all properties and methods of AliasInfo objects, type "get-alias | get-member".

Example 5

C:\PS>get-alias -definition "*-pssession" -exclude e* -scope global

This example gets aliases for commands that have names that end in "-pssession", except for those that begin with "e".

The command uses the Scope parameter to apply the command in the global scope. This is useful in scripts when you want to get the aliases in the session.

See Also

  • about_Aliases
  • Set-Alias
  • New-Alias
  • Export-Alias
  • Import-Alias
  • Alias Provider


Get-AuthenticodeSignature

Gets information about the Authenticode signature in a file.

Syntax

Get-AuthenticodeSignature [-FilePath] <string[]> [<CommonParameters>]

Description

The Get-AuthenticodeSignature cmdlet gets information about the Authenticode signature in a file. If the file is not signed, the information is retrieved, but the fields are blank.

Parameters

-FilePath <string[]>

Specifies the path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("FilePath") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a file path to Get-AuthenticodeSignature.
Outputs | System.Management.Automation.Signature Get-AuthenticodeSignature returns a signature object for each signature that it gets.

Notes

For information about Authenticode signatures in Windows PowerShell, see about_Signing.

Example 1

C:\PS>get-AuthenticodeSignature -filepath C:\Test\NewScript.ps1

This command gets information about the Authenticode signature in the NewScript.ps1 file. It uses the FilePath parameter to specify the file.

Example 2

C:\PS>get-authenticodesignature test.ps1, test1.ps1, sign-file.ps1, makexml.ps1

This command gets information about the Authenticode signature in the four files listed at the command line. In this command, the name of the FilePath parameter, which is optional, is omitted.

Example 3

C:\PS>get-childitem $pshome\*.* | foreach-object {Get-AuthenticodeSignature $_} | where {$_.status -eq "Valid"}

This command lists all of the files in the $pshome directory that have a valid Authenticode signature. The $pshome automatic variable contains the path to the Windows PowerShell installation directory.

The command uses the Get-ChildItem cmdlet to get the files in the $pshome directory. It uses a pattern of *.* to exclude directories (although it also excludes files without a dot in the filename).

The command uses a pipeline operator (|) to send the files in $pshome to the Foreach-Object cmdlet, where Get-AuthenticodeSignature is called for each file.

The results of the Get-AuthenticodeSignature command are sent to a Where-Object command that selects only the signature objects with a status of "Valid".

See Also

  • about_Signing
  • about_Execution_Policies
  • Set-AuthenticodeSignature
  • Get-ExecutionPolicy
  • Set-ExecutionPolicy


Get-ChildItem

Gets the items and child items in one or more specified locations.

Syntax

Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Exclude <string[]>] [-Force] [-Include <string[]>] [-Name] [-Recurse] [-UseTransaction] [<CommonParameters>]

Get-ChildItem [-LiteralPath] <string[]> [[-Filter] <string>] [-Exclude <string[]>] [-Force] [-Include <string[]>] [-Name] [-Recurse] [-UseTransaction] [<CommonParameters>]

Description

The Get-ChildItem cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child items. You can use the Recurse parameter to get items in all child containers.

A location can be a file system location, such as a directory, or a location exposed by another provider, such as a registry hive or a certificate store.

Parameters

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to get items that cannot otherwise not be accessed by the user, such as hidden or system files. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Retrieves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

The Include parameter is effective only when the command includes the Recurse parameter or the path leads to the contents of a directory, such as C:\Windows\*, where the wildcard character specifies the contents of the C:\Windows directory.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to one or more locations. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name

Retrieves only the names of the items in the locations. If you pipe the output of this command to another command, only the item names are sent.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Recurse

Gets the items in the specified locations and in all child items of the locations.

Recurse works only when the path points to a container that has child items, such as C:\Windows or C:\Windows\*, and not when it points to items that do not have child items, such as C:\Windows\*.exe.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Get-ChildItem.
Outputs | Object. The type of object that Get-ChildItem returns is determined by the provider with which it is used.

Notes

You can also refer to Get-ChildItem by its built-in aliases, "ls", "dir", and "gci". For more information, see about_Aliases.

Get-ChildItem does not get hidden items by default. To get hidden items, use -Force.

The Get-ChildItem cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>get-childitem

This command gets the child items in the current location. If the location is a file system directory, it gets the files and sub-directories in the current directory. If the item does not have child items, this command returns to the command prompt without displaying anything.

The default display lists the mode (attributes), last write time, file size (length), and the name of the file. The valid values for mode are d (directory), a (archive), r (read-only), h (hidden), and s (system).

Example 2

C:\PS>get-childitem . -include *.txt -recurse -force

This command retrieves all of the .txt files in the current directory and its subdirectories. The dot (.) represents the current directory and the Include parameter specifies the file name extension. The Recurse parameter directs Windows PowerShell to retrieve objects recursively, and it indicates that the subject of the command is the specified directory and its contents. The force parameter adds hidden files to the display.

Example 3

C:\PS>get-childitem c:\windows\logs\* -include *.txt -exclude A*

This command lists the .txt files in the Logs subdirectory, except for those whose names start with the letter A. It uses the wildcard character (*) to indicate the contents of the Logs subdirectory, not the directory container. Because the command does not include the Recurse parameter, Get-ChildItem does not include the content of directory automatically; you need to specify it.

Example 4

C:\PS>get-childitem registry::hklm\software

This command retrieves all of the registry keys in the HKEY_LOCAL_MACHINE\SOFTWARE key in the registry of the local computer.

Example 5

C:\PS>get-childitem -name

This command retrieves only the names of items in the current directory.

Example 6

C:\PS>get-childitem cert:\. -recurse -codesigningcert

This command gets all of the certificates in the certificate store that have code-signing authority.

The command uses the Get-ChildItem cmdlet. The path specifies the Cert: drive exposed by the Windows PowerShell certificate provider. The backslash (\) symbol specifies a subdirectory of the certificate store and the dot (.) represents the current directory, which would be the root directory of the certificate store. The Recurse parameter specifies a recursive search.

The CodeSigningCertificate parameter is a dynamic parameter that gets only certificates with code-signing authority. For more information, type "get-help certificate".

Example 7

C:\PS>get-childitem * -include *.exe

This command retrieves all of the items in the current directory with a ".exe" file name extension. The wildcard character (*) represents the contents of the current directory (not the container). When using the Include parameter without the Recurse parameter, the path must point to contents, not a container.

See Also

  • about_Providers
  • Get-Item
  • Get-Alias
  • Get-Location
  • Get-Process


Get-Command

Gets basic information about cmdlets and other elements of Windows PowerShell commands.

Syntax

Get-Command [[-Name] <string[]>] [-CommandType {<Alias> | <Function> | <Filter> | <Cmdlet> | <ExternalScript> | <Application> | <Script> | <All>}] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-Syntax] [-TotalCount <int>] [<CommonParameters>]

Get-Command [-Noun <string[]>] [-Verb <string[]>] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-Syntax] [-TotalCount <int>] [<CommonParameters>]

Description

The Get-Command cmdlet gets basic information about cmdlets and other elements of Windows PowerShell commands in the session, such as aliases, functions, filters, scripts, and applications.

Get-Command gets its data directly from the code of a cmdlet, function, script, or alias, unlike Get-Help, which gets its information from help topic files.

Without parameters, "Get-Command" gets all of the cmdlets and functions in the current session. "Get-Command *" gets all Windows PowerShell elements and all of the non-Windows-PowerShell files in the Path environment variable ($env:path). It groups the files in the "Application" command type.

You can use the Module parameter of Get-Command to find the commands that were added to the session by adding a Windows PowerShell snap-in or importing a module.

Parameters

-ArgumentList <Object[]>

Gets information about a cmdlet or function when it is used with the specified parameters ("arguments"), such as a path. The alias for ArgumentList is Args.

To detect parameters that are added to a cmdlet when it is used with a particular provider, set the value of ArgumentList to a path in the provider drive, such as "HKML\Software" or "cert:\my".

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CommandType <CommandTypes>

Gets only the specified types of commands. Use "CommandType" or its alias, "Type". By default, Get-Command gets cmdlets and functions.

Valid values are:

-- Alias: All Windows PowerShell aliases in the current session.

-- All: All command types. It is the equivalent of "get-command *".

-- Application: All non-Windows-PowerShell files in paths listed in the Path environment variable ($env:path), including .txt, .exe, and .dll files.

-- Cmdlet: The cmdlets in the current session. "Cmdlet" is the default.

-- ExternalScript: All .ps1 files in the paths listed in the Path environment variable ($env:path).

-- Filter and Function: All Windows PowerShell functions.

-- Script: Script blocks in the current session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Module <string[]>

Gets the commands that came from the specified modules or snap-ins. Enter the names of modules or snap-ins, or enter snap-in or module objects.

You can refer to this parameter by its name, Module, or by its alias, PSSnapin. The parameter name that you choose has no effect on the command or its output.

This parameter takes string values, but you can also supply a PSModuleInfo or PSSnapinInfo object, such as the objects that Get-Module, Get-PSSnapin, and Import-PSSession return.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Gets information only about the cmdlets or command elements with the specified name. <String> represents all or part of the name of the cmdlet or command element. Wildcards are permitted.

To list commands with the same name in execution order, type the command name without wildcard characters. For more information, see the Notes section.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Noun <string[]>

Gets cmdlets and functions with names that include the specified noun. <String> represents one or more nouns or noun patterns, such as "process" or "*item*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Syntax

Gets only specified data about the command element.

* For aliases, retrieves the standard name.

* For cmdlets, retrieves the syntax.

* For functions and filters, retrieves the function definition.

* For scripts and applications (files), retrieves the path and filename.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-TotalCount <int>

Gets only the specified number of command elements. You can use this parameter to limit the output of a command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Verb <string[]>

Gets information about cmdlets and functions with names that include the specified verb. <String> represents one or more verbs or verb patterns, such as "remove" or *et". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a "Name", "Command", and "Verb" noun-property specified, or a string object to Get-Command.
Outputs | Object The type of object returned depends on the type of command element retrieved. For example, Get-Command on a cmdlet retrieves a CmdletInfo object, while Get-Command on a DLL retrieves an ApplicationInfo object.

Notes

Without parameters, "Get-Command" gets information about the Windows PowerShell cmdlets and functions. Use the parameters to qualify the elements retrieved.

Unlike Get-Help, which displays the contents of XML-based help topic files, Get-Command gets its cmdlet information directly from the cmdlet code in the system.

Get-Command returns the commands in alphabetical order. When the session contains more than one command with the same name, Get-Command returns the commands in execution order. The first command that is listed is the command that runs when you type the command name without qualification. For more information, see about_Command_Precedence.

Example 1

C:\PS>get-command

This command gets information about all of the Windows PowerShell cmdlets and functions.

The default display lists the command type ("Cmdlet" or "Function" or "Filter"), the name of the cmdlet or function, and the syntax or function definition.

Example 2

C:\PS>get-command -verb set | format-list

This command gets information about all of the cmdlets and functions with the verb "set", and it displays some of that information in a list.

The list format includes fields that are omitted from the table display, including the complete syntax. To display all fields (all properties of the object), type "get-command -verb set | format-list *".

Example 3

C:\PS>get-command -type cmdlet | sort-object noun | format-table -group noun

This command retrieves all of the cmdlets, sorts them alphabetically by the noun in the cmdlet name, and then displays them in noun-based
groups. This display can help you find the cmdlets for a task.

By default, Get-Command displays items in the order in which the system discovers them, which is also the order in which they are selected to run when a run command is ambiguous.

Example 4

C:\PS>get-command -module Microsoft.PowerShell.Security, TestModule

This command gets the commands in the Microsoft.PowerShell.Security snap-in and the Test-Module module.

The Module parameter gets commands that were added by importing modules or adding Windows PowerShell snap-ins.

Example 5

C:\PS>get-command get-childitem -args cert: -syntax

This command retrieves information about the Get-ChildItem cmdlet when Get-ChildItem is used with the Windows PowerShell Certificate provider.

When you compare the syntax displayed in the output with the syntax that is displayed when you omit the Args (ArgumentList) parameter, you'll see that the Certificate provider dynamically adds a parameter, CodeSigningCert, to the Get-ChildItem cmdlet.

Example 6

C:\PS>(get-command get-childitem -ArgumentList cert:).parametersets[0].parameters | where-object { $_.IsDynamic }

This command retrieves only parameters that are added to the Get-ChildItem cmdlet dynamically when it is used with the Windows PowerShell Certificate provider. This is an alternative to the method used in the previous example.

In this command, the "get-command get-childitem -ArgumentList cert:" is processed first. It requests information from Get-Command about the Get-ChildItem cmdlet when it is used with the Certificate provider. The ".parametersets[0]" selects the first parameter set (set 0) of "get-childitem -argumentList cert:" and ".parameters" selects the parameters in that parameter set. The resulting parameters are piped to the Where-Object cmdlet to test each parameter ("$_.") by using the IsDynamic property. To find the properties of the objects in a command, use Get-Member.

Example 7

C:\PS>get-command *

This command gets information about the Windows PowerShell cmdlets, functions, filters, scripts, and aliases in the current console.

It also gets information about all of the files in the paths of the Path environment variable ($env:path). It returns an ApplicationInfo object (System.Management.Automation.ApplicationInfo) for each file, not a FileInfo object (System.IO.FileInfo).

Example 8

C:\PS>get-command | where-object {$_.definition -like "*first*"}

CommandType     Name                        Definition
-----------     ----                        ---------
Cmdlet          Select-Object               Select-Object [[-Property]

Description
-----------
This command finds a cmdlet or function based on the name of one of its parameters. You can use this command to identify a cmdlet or function when all that you can recall is the name of one of its parameters.

In this case, you recall that one of the cmdlets or functions has a First parameter that gets the first "n" objects in a list, but you cannot remember which cmdlet it is.

This command uses the Get-Command cmdlet to get a CmdletInfo object representing each of the cmdlets and functions in the session. The CmdletInfo object has a Definition property that contains the syntax of the cmdlet or function, which includes its parameters.

The command uses a pipeline operator (|) to pass the CmdletInfo object to the Where-Object cmdlet, which examines the definition (syntax) of each object ($_) for a value that includes "first".

The result shows that the First parameter belongs to the Select-Object cmdlet.

Example 9

C:\PS>get-command dir | format-list

Name              : dir
CommandType       : Alias
Definition        : Get-ChildItem
ReferencedCommand : Get-ChildItem
ResolvedCommand   : Get-ChildItem

Description
-----------
This example shows how to use the Get-Command cmdlet with an alias. Although it is typically used on cmdlets, Get-Command also displays information about the code in scripts, functions, aliases, and executable files.

This command displays the "dir" alias in the current console. The command pipes the result to the Format-List cmdlets.

Example 10

C:\PS>get-command notepad

CommandType     Name           Definition
-----------     ----           ----------
Application     notepad.exe    C:\WINDOWS\system32\notepad.exe
Application     NOTEPAD.EXE    C:\WINDOWS\NOTEPAD.EXE

Description
-----------
This example shows how to use Get-Command to determine which command Windows PowerShell runs when it has access to multiple commands with the same name. When you use the Name parameter without wildcard characters, Get-Command lists the commands with that name in execution precedence order.

This command shows which Notepad program Windows PowerShell runs when you type "Notepad" without a fully qualified path. The command uses the Name parameter without wildcard characters.

The sample output shows the Notepad commands in the current console. It indicates that Windows PowerShell will run the instance of Notepad.exe in the C:\Windows\System32 directory.

Example 11

C:\PS>(get-command get-date).pssnapin

C:\PS> (get-command remove-gpo).module

Description
-----------
These commands show how to find the snap-in or module from which a particular cmdlet originated.

The first command uses the PSSnapin property of the CmdletInfo object to find the snap-in that added the Get-Date cmdlet.

The second command uses the Module property of the CmdletInfo object to find the module that added the Remove-GPO cmdlet.

See Also

  • about_Command_Precedence
  • Get-Help
  • Get-PSDrive
  • Get-Member
  • Import-PSSession
  • Export-PSSession


Get-ComputerRestorePoint

Gets the restore points on the local computer.

Syntax

Get-ComputerRestorePoint [[-RestorePoint] <Int32[]>] [<CommonParameters>]

Get-ComputerRestorePoint -LastStatus [<CommonParameters>]

Description

The Get-ComputerRestorePoint cmdlet gets the restore points on the local computer. This cmdlet can also display the status of the most recent attempt to restore the computer.

You can use the information returned by Get-ComputerRestorePoint to select a restore point, and you can use the sequence number to identify a restore point for the Restore-Computer cmdlet.

Parameters

-LastStatus

Gets the status of the most recent system restore operation.

Required? | true
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RestorePoint <Int32[]>

Gets the restore points with the specified sequence numbers. Enter the sequence numbers of one or more restore points. By default, Get-ComputerRestorePoint gets all restore points on the local computer.

Required? | false
Position? | 1
Default Value | All restore points
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to this cmdlet.
Outputs | System.Management.ManagementObject#root\default\SystemRestore or String. Get-ComputerRestore returns a SystemRestore object, which is an instance of the WMI SystemRestore class. When you use the LastStatus parameter, this cmdlet returns a string.

Notes

To run a Get-ComputerRestorePoint command on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administrator" option.

This cmdlet uses the Windows Management Instrumentation (WMI) SystemRestore class.

Example 1

C:\PS>get-computerrestorepoint

This command gets all of the restore points on the local computer.

Example 2

C:\PS>get-computerrestorepoint -restorepoint 232, 240, 245

This command gets the restore points with sequence numbers 232, 240, and 245.

Example 3

C:\PS>get-computerrestorepoint -laststatus

The last restore failed.

Description
-----------
This command displays the status of the most recent system restore operation on the local computer.

Example 4

C:\PS>get-computerrestorepoint | format-table SequenceNumber, @{Label="Date"; Expression={$_.ConvertToDateTime($_.CreationTime)}}, Description -auto

SequenceNumber Date                  Description
-------------- ----                  -----------
           253 8/5/2008 3:19:20 PM   Windows Update
           254 8/6/2008 1:53:24 AM   Windows Update
           255 8/7/2008 12:00:04 AM  Scheduled Checkpoint
...

Description
-----------
This command displays the restore points in a table for easy reading.

The Format-Table command includes a calculated property that uses the ConvertToDateTime method to convert the value of the CreationTime property from WMI format to a DateTime object.

Example 5

C:\PS>((get-computerrestorepoint)[-1]).sequencenumber

This command gets the sequence number of the most recently created restore point on the computer.

The command uses the -1 index to get the last item in the array that Get-ComputerRestorePoint returns.

See Also

  • Enable-ComputerRestore
  • Disable-ComputerRestore
  • Restore-Computer
  • Restart-Computer


Get-Content

Gets the content of the item at the specified location.

Syntax

Get-Content [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-ReadCount <Int64>] [-TotalCount <Int64>] [-UseTransaction] [<CommonParameters>]

Get-Content [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-ReadCount <Int64>] [-TotalCount <Int64>] [-UseTransaction] [<CommonParameters>]

Description

The Get-Content cmdlet gets the content of the item at the location specified by the path, such as the text in a file. It reads the content one line at a time and returns an object for each line.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers that are installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Overrides restrictions that prevent the command from succeeding, just so the changes do not compromise security. For example, Force will override the read-only attribute or create directories to complete a file path, but it will not attempt to change file permissions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Retrieves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the path to an item. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to an item. Get-Content retrieves the content of the item. Wildcards are permitted. The parameter name ("Path" or "FilePath") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-ReadCount <Int64>

Specifies how many lines of content are sent through the pipeline at a time. The default value is 1. A value of 0 (zero) sends all of the content at one time.

This parameter does not change the content displayed, but it does affect the time it takes to display the content. As the value of ReadCount increases, the time it takes to return the first line increases, but the total time for the operation decreases. This can make a perceptible difference in very large items.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-TotalCount <Int64>

Specifies how many lines of content are retrieved. The default is -1 (all lines).

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to Get-Content.
Outputs | Object Get-Content returns objects that represent the content that it gets. The object type depends on the content type.

Notes

You can also refer to Get-Content by its built-in aliases, "cat", "type" and "gc". For more information, see about_Aliases.

The Get-Content cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>get-content -Path C:\Chapters\chapter1.txt

This command displays the content of the Chapter1.txt file on the console. It uses the Path parameter to specify the name of the item. Get-Content actually passes the content down the pipeline, but because there are no other pipeline elements, the content is formatted and displayed on the console.

Example 2

C:\PS>get-content c:\Logs\Log060912.txt -totalcount 50 | set-content sample.txt

This command gets the first 50 lines of the Log060912.txt file and stores them in the sample.txt file. The command uses the Get-Content cmdlet to get the text in the file. (The name of Path parameter, which is optional, is omitted.) The TotalCount parameter limits the retrieval to the first 50 lines. The pipeline operator (|) sends the result to Set-Content, which places it in the sample.txt file.

Example 3

C:\PS>(get-content cmdlets.txt -totalcount 5)[-1]

This command gets the fifth line of the Cmdlets.txt text file. It uses the TotalCount parameter to get the first five lines and then uses array notation to get the last line (indicated by "-1") of the resulting set.

See Also

  • about_Providers
  • Add-Content
  • Set-Content
  • Clear-Content


Get-Counter

Gets performance counter data from local and remote computers.

Syntax

Get-Counter [-Counter] <string[]> [-ComputerName <string[]>] [-Continuous] [-MaxSamples <Int64>] [-SampleInterval <int>] [<CommonParameters>]

Get-Counter -ListSet <string[]> [-ComputerName <string[]>] [<CommonParameters>]

Description

The Get-Counter cmdlet gets live, real-time performance counter data directly from the performance monitoring instrumentation in Windows. You can use it to get performance data from the local or remote computers at the sample interval that you specify.

Without parameters, a "Get-Counter" command gets counter data for a set of system counters.

You can use the parameters of Get-Counter to specify one or more computers, to list the performance counter sets and the counters that they contain, and to set the sample size and interval.

Parameters

-ComputerName <string[]>

Gets data from the specified computers. Type the NetBIOS name, an Internet Protocol (IP) address, or the fully qualified domain names of the computers. The default value is the local computer.

Note: Get-Counter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-Counter even if your computer is not configured for remoting in Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Continuous

Gets samples continuously until you press CTRL+C. By default, Get-Counter gets only one counter sample. You can use the SampleInterval parameter to set the interval for continuous sampling.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Counter <string[]>

Gets data from the specified performance counters. Enter one or more counter paths. Wildcards are permitted only in the Instance value. You can also pipe counter path strings to Get-Counter.

Each counter path has the following format:

"[\\<ComputerName>]\<CounterSet>(<Instance>)\<CounterName>"

For example:

"\\Server01\Processor(2)\% User Time".

The <ComputerName> element is optional. If you omit it, Get-Counter uses the value of the ComputerName parameter.

Note: To get correctly formatted counter paths, use the ListSet parameter to get a performance counter set. The Paths and PathsWithInstances properties of each performance counter set contain the individual counter paths formatted as a string. You can save the counter path strings in a variable or pipe the string directly to another Get-Counter command. For a demonstration, see the examples.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | true

-ListSet <string[]>

Gets the specified performance counter sets on the computers. Enter the names of the counter sets. Wildcards are permitted. You can also pipe counter set names to Get-Counter.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | true

-MaxSamples <Int64>

Specifies the number of samples to get from each counter. The default is 1 sample. To get samples continuously (no maximum sample size), use the Continuous parameter.

To collect a very large data set, consider running a Get-Counter command as a Windows PowerShell background job. For more information, see about_Jobs and Start-Job.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SampleInterval <int>

Specifies the time between samples in seconds. The minimum value and the default value are 1 second.

Required? | false
Position? | named
Default Value | 1
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs

System.String[]. You can pipe counter paths and counter set (ListSet) names to Get-Counter.

System.String[]. You can pipe counter paths and counter set (ListSet) names to Get-Counter.

Outputs

Microsoft.PowerShell.Commands.GetCounter.CounterSet, Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet, Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample

The ListSet parameter gets Microsoft.PowerShell.Commands.GetCounter.CounterSet objects. The Counter parameter gets Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet objects. Each counter value is a Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample object.

Notes

Performance counters are often protected by access control lists (ACLs). To get all available performance counters, open Windows PowerShell with the "Run as administrator" option.

By default, Get-Counter gets one sample during a one-second sample interval. To change this behavior, use the MaxSamples and Continuous parameters.

The MaxSamples and SampleInterval values that you set apply to all the counters on all the computers in the command. To set different values for different counters, enter separate Get-Counter commands for each counter.

Example 1

C:\PS>get-counter -ListSet *

This command gets all of the counter sets on the local computer.

Because many of the counter sets are protected by access control lists (ACLs), to see all counter sets, open Windows PowerShell with the "Run as administrator" option before using the Get-Counter command.

Example 2

C:\PS>get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 3

This command gets the current "% Processor Time" combined values for all processors on the local computer. It collects data every 2 seconds until it has three values.

Example 3

C:\PS>get-counter -listset * | sort-object  countersetname | format-table countersetname

This command gets an alphabetically sorted list of the names of all of the counter sets on the local computer.

Example 4

C:\PS>(get-counter -listset memory).paths

C:\PS> (get-counter -listset memory).paths | where {$_ -like "*cache*"}

C:\PS> (get-counter -listset memory).paths

\Memory\Page Faults/sec
\Memory\Available Bytes
\Memory\Committed Bytes
\Memory\Commit Limit
\Memory\Write Copies/sec
\Memory\Transition Faults/sec
\Memory\Cache Faults/sec
\Memory\Demand Zero Faults/sec
\Memory\Pages/sec
\Memory\Pages Input/sec
...

C:\PS> (get-counter -listset memory).paths | where {$_ -like "*cache*"}

\Memory\Cache Faults/sec
\Memory\Cache Bytes
\Memory\Cache Bytes Peak
\Memory\System Cache Resident Bytes
\Memory\Standby Cache Reserve Bytes
\Memory\Standby Cache Normal Priority Bytes
\Memory\Standby Cache Core Bytes

Description
-----------
These commands use the Path property of a counter set to find the correctly formatted path names for the performance counters. You can use a command like this one to get the correct counter path names.

The first command gets the path names of the performance counters in the Memory counter set on the local computer.

The second command gets the path names that include "cache".

Example 5

C:\PS>$diskreads = "\LogicalDisk(C:)\Disk Reads/sec"

C:\PS> $diskreads | get-counter -computer Server01, Server02 -maxsamples 10

These commands get the Disk Reads/sec counter data from the Server01 and Server02 computers. The second command uses the MaxSamples parameter to limit the return to 10 samples.

Example 6

C:\PS>(get-counter -list physicaldisk).pathswithinstances

This command gets the correctly formatted path names for the PhysicalDisk  performance counters, including the instance names.

Example 7

C:\PS>C:\PS> $servers = get-random (get-content servers.txt) -count 50

C:\PS> $counter = "\Processor(*)\% DPC Time"

C:\PS> get-counter -Counter $counter -computername $servers

These commands get the value of the "% DPC Time" performance counter on 50 randomly select computers in the enterprise.

The first command uses the Get-Content cmdlet to get the list of enterprise servers from the Servers.txt file. It uses the Get-Random cmdlet to select 50 server names randomly from the Servers.txt file contents. The results are saved in the $servers variable.

The second command saves the counter path to the "% DPC Time" cmdlet in the $Counter variable. The counter path includes a wildcard character in the instance name to get the data on all of the processors on each of the computers.

The third command uses the Get-Counter cmdlet to get the counter values. It uses the Counter parameter to specify the counters and the ComputerName parameter to specify the computers saved in the $servers variable.

Example 8

C:\PS>$memCounters = (get-counter -list memory).paths

C:\PS> get-counter -counter $memCounters

These commands get a single value for all of the performance counters in the memory counter set on the local computer.

The first command gets the counter paths and saves them in the $memCounters variable.

The second command uses the Get-Counter cmdlet to get the counter data for each counter. It uses the Counter parameter to specify the counters in $memCounters.

Example 9

C:\PS>$counter = "\\SERVER01\Process(Idle)\% Processor Time"

C:\PS> $data = get-counter $counter

C:\PS> $data.countersamples | format-list -property *

Path             : \\SERVER01\process(idle)\% processor time
InstanceName     : idle
CookedValue      : 198.467899571389
RawValue         : 14329160321003
SecondValue      : 128606459528326201
MultipleCount    : 1
CounterType      : Timer100Ns
Timestamp        : 7/15/2008 6:39:12 PM
Timestamp100NSec : 128606207528320000
Status           : 0
DefaultScale     : 0
TimeBase         : 10000000

Description
-----------
This example shows the property values in the PerformanceCounterSample object that represents each data sample.

The first command saves a counter path in the $counter variable.

The second command uses the Get-Counter cmdlet to get one sample of the counter values. It saves the results in the $data variable.

The third command uses the Format-List cmdlet to display all the properties of the CounterSamples property of the sample set object as a list.

You can use the properties of the CounterSamples object to examine, select, sort,  and group the data.

Example 10

C:\PS>$counters = "\LogicalDisk(_Total)\% Free Space"

C:\PS> start-job -scriptblock {get-counter -counter $counters -maxsamples 1000)

The command runs a Get-Counter command as background job. For more information, see Start-Job.

Example 11

C:\PS>get-counter -computername (get-random servers.txt -count 50) -counter "\LogicalDisk(*)\% Free Space"

This command uses the Get-Counter and Get-Random cmdlets to find the percentage of free disk space on 50 computers selected randomly from the Servers.txt file.

Example 12

C:\PS>$a = get-counter "\LogicalDisk(_Total)\% Free Space" -comp s1, s2

C:\PS> $a

C:\PS> $a.countersamples | format-table -auto

C:\PS> $a.countersamples[0] | format-table -property *

C:\PS> $a.countersamples | where {$_.cookedvalue -lt 15}

C:\PS> $a

Counter Paths: \\s1\\logicaldisk(c:)\% free space, \\s1\\logicaldisk(d:)\% free space, \\s1\\logicaldisk(_total)\% free space, \\s2\\logicaldisk(c:)\% free space, \\s2\\logicaldisk(_total)\% free space

Timestamp     : 7/15/2008 5:09:08 PM
Cooked Values : "0.327058823529412", "17.8952248493278", "12.9994033060778", "75.0754805595626", "75.0754805595626"

C:\PS> $a.countersamples | format-table -auto

Path                                     InstanceName       CookedValue
----                                     ------------       -----------
\\s1\\logicaldisk(c:)\% free space       c:           0.327058823529412
\\s1\\logicaldisk(d:)\% free space       d:            17.8952248493278
\\s1\\logicaldisk(_total)\% free space   _total        12.9994033060778
\\s2\\logicaldisk(c:)\% free space       c:            75.0754805595626
\\s2\\logicaldisk(_total)\% free space   _total        75.0754805595626

C:\PS> ($a.countersamples)[0] | fl *

Path             : \\s1\\logicaldisk(c:)\% free space
InstanceName     : c:
CookedValue      : 0.327058823529412
RawValue         : 139
SecondValue      : 42500
MultipleCount    : 1
CounterType      : RawFraction
Timestamp        : 7/15/2008 5:09:08 PM
Timestamp100NSec : 128606153488500000
Status           : 0
DefaultScale     : 0
TimeBase         : 3312060

C:\PS> $a.countersamples | where {$_.cookedvalue -lt 15}

Path                                     InstanceName       CookedValue
----                                     ------------       -----------
\\s1\\logicaldisk(c:)\% free space       c:           0.327058823529412
\\s1\\logicaldisk(_total)\% free space   _total        12.9994033060778

Description
-----------
This example shows how to associate counter data with the computer on which it originated, and how to manipulate the data.

The first command uses the Get-Counter cmdlet to get the "LogicalDisk\% Free Space" counter value from two remote computers, S1 and S2. It saves the result in the $a variable.

The second command displays the results in the $a variable. All of the data is stored in the object, but it is not easy to see it in this form.

The third command displays in a table the value of the CounterSamples property of the PerformanceCounterSampleSet object that Get-Counter returns. (To see all of the properties and methods of the object, pipe it to the Get-Member cmdlet.)

The CounterSamples property contains a PerformanceCounterSample object with its own properties and methods. The fourth command uses array notation to get the first counter sample and a pipeline operator to send the counter sample object to the Format-List cmdlet, which displays all of its properties and methods in a list. This display shows the richness of the data in each counter sample object.

The fourth command shows how to select data from the counter samples. It uses the Where-Object cmdlet to get only the counter samples with a CookedValue of less than 15.

Example 13

C:\PS>$p = get-counter '\Process(*)\% Processor Time'

C:\PS> $p.CounterSamples | sort-object -property CookedValue -Descending | format-table -auto

Path                                              InstanceName      CookedValue
----                                              ------------      -----------
\\server01\process(_total)\% processor time        _total        200.00641042078
\\server01\process(idle)\% processor time          idle          200.00641042078
\\server01\process(explorer#1)\% processor time    explorer                    0
\\server01\process(dwm#1)\% processor time         dwm                         0
\\server01\process(taskeng#1)\% processor time     taskeng                     0
\\server01\process(taskhost#1)\% processor time    taskhost                    0
\\server01\process(winlogon)\% processor time      winlogon                    0
\\server01\process(csrss)\% processor time         csrss                       0

Description
-----------
This example shows how to sort the performance counter data that you retrieve. The example finds the processes on the computer that are using the most processor time during the sampling.

The first command gets the "Process\% Processor Time" counter for all the processes on the computer. The command saves the results in the $p variable.

The second command gets the CounterSamples property of the sample set object in $p and it sorts the samples in descending order based on the cooked value of the sample. The command uses the Format-Table cmdlet and its AutoFormat parameter to position the columns in the table.

Example 14

C:\PS>$ws = get-counter "\Process(*)\Working Set - Private"

C:\PS> $ws.countersamples | sort-object -property cookedvalue -descending | format-table -property InstanceName, CookedValue -auto

InstanceName  CookedValue
------------  -----------
_total          162983936
svchost          40370176
powershell       15110144
explorer         14135296
svchost          10928128
svchost           9027584
...

Description
-----------
These commands find the processes on the computer with the largest working sets. They list the processes in descending order based on their working set size.

The first command gets one sample of the "Process\Working Set - Private" counter for each process. The command saves the counter data in the $ws variable.

The second command uses a pipeline operator (|) to send the data in the CounterSamples property of the $ws variable to the Sort-Object cmdlet, where the process data is sorted in descending order by the value of the CookedValue property. Another pipeline sends the sorted data to the Format-Table cmdlet, where the data is formatted as a table with InstanceName and CookedValue columns.

Example 15

C:\PS>get-counter -counter "\processor(_total)\% processor time" -continuous

This command gets a series of samples of the Processor\% Processor Time counter at the default one second interval. To stop the command, press CTRL + C.

See Also

  • Import-Counter
  • Export-Counter


Get-Credential

Gets a credential object based on a user name and password.

Syntax

Get-Credential [-Credential] <PSCredential> [<CommonParameters>]

Description

The Get-Credential cmdlet creates a credential object for a specified user name and password. You can use the credential object in security operations.

The cmdlet prompts the user for a password or user name and password. Users are prompted through a dialog box or at the command line, depending on the system registry setting.

Parameters

-Credential <PSCredential>

Specifies a user name for the credential, such as "User01" or "Domain01\User01". The parameter name ("Credential") is optional.

When you submit the command, you will be prompted for a password.

If you enter a user name without a domain, Get-Credential inserts a backslash before the name.

If you omit this parameter, you will be prompted for a user name and a password.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.PSCredential Get-Credential returns a credential object.

Notes

You can use the PSCredential object that Get-Credential creates in cmdlets that request user authentication, such as those with a Credential parameter.

The Credential parameter is not supported by the providers that are installed with Windows PowerShell. However, you can use the Credential parameter with Get-WmiObject, because it calls the Microsoft .NET Framework directly.

Example 1

C:\PS>$c = Get-Credential

This command gets a credential object and saves it in the $c variable.

When you enter the command, a dialog box appears requesting a user name and password. When you enter the requested information, the cmdlet creates a PSCredential object representing the credentials of the user and saves it in the $c variable.

You can use the object as input to cmdlets that request user authentication, such as those with a Credential parameter. However, the providers that are installed with Windows PowerShell do not support the Credential parameter.

Example 2

C:\PS>$c = Get-Credential

C:\PS>Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c

These commands use a credential object from Get-Credential to authenticate a user on a remote computer so they can use Windows Management Instrumentation (WMI) to manage the computer.

The first command gets a credential object and saves it in the $c variable. The second command uses the credential object in a Get-WmiObject command. This command gets information about the disk drives on the Server01 computer.

Example 3

C:\PS>C:\PS>Get-WmiObject Win32_BIOS -ComputerName Server01 '
-Credential (get-credential Domain01\User01)

This command shows how to include a Get-Credential command in a Get-WmiObject command.

This command uses the Get-WmiObject cmdlet to get information about the BIOS on the Server01 computer. It uses the Credential parameter to authenticate the user, Domain01\User01, and a Get-Credential command as the value of the Credential parameter.

Example 4

C:\PS>$c = Get-Credential -credential User01

C:\PS>$c.Username

\User01

Description
-----------
This example creates a credential that includes a user name without a domain name. It demonstrates that Get-Credential inserts a backslash before the user name.

The first command gets a credential with the user name User01 and stores it in the $c variable.

The second command displays the value of the Username property of the resulting credential object.

Example 5

C:\PS>$credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "NetBiosUserName")

This command uses the PromptForCredential method to prompt the user for their user name and password. The command saves the resulting credentials in the $credential variable.

PromptForCredential is an alternative to using Get-Credential. When you use PromptForCredential, you can specify the caption, messages, and user name that appear in the message box.

Example 6

C:\PS>Set-ItemProperty 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds' ConsolePrompting $true

When requiring a user name and password, as a default, a dialog box appears to prompt the user. To be prompted at the command line, modify the registry by running this command in Windows PowerShell Run as administrator.

Use the same command with "ConsolePrompting $false" to be prompted with a dialog box.


Get-Culture

Gets the current culture set in the operating system.

Syntax

Get-Culture [<CommonParameters>]

Description

The Get-Culture cmdlet gets information about the current culture settings. This includes information about the current language settings on the system, such as the keyboard layout, and the display format of items such as numbers, currency, and dates.

You can also use the Get-UICulture cmdlet, which gets the current user interface culture on the system. The user-interface (UI) culture determines which text strings are used for user interface elements, such as menus and messages.

Parameters

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Globalization.CultureInfo Get-Culture returns an object that represents the current culture.

Notes

You can also use the $PsCulture and $PsUICulture variables. The $PsCulture variable stores the name of the current culture and the $PsUICulture variable stores the name of the current UI culture.

Example 1

C:\PS>get-culture

This command displays information about the regional settings on the computer.

Example 2

C:\PS>$c = get-culture

C:\PS> $c | format-list -property *

Parent                         : en
LCID                           : 1033
KeyboardLayoutId               : 1033
Name                           : en-US
IetfLanguageTag                : en-US
DisplayName                    : English (United States)
NativeName                     : English (United States)
EnglishName                    : English (United States)
TwoLetterISOLanguageName       : en
ThreeLetterISOLanguageName     : eng
ThreeLetterWindowsLanguageName : ENU
CompareInfo                    : CompareInfo - 1033
TextInfo                       : TextInfo - 1033
IsNeutralCulture               : False
CultureTypes                   : SpecificCultures, InstalledWin32Cultures, FrameworkCultures
NumberFormat                   : System.Globalization.NumberFormatInfo
DateTimeFormat                 : System.Globalization.DateTimeFormatInfo
Calendar                       : System.Globalization.GregorianCalendar
OptionalCalendars              : {System.Globalization.GregorianCalendar, System.Globalization.GregorianCalendar}
UseUserOverride                : True
IsReadOnly                     : False

C:\PS> $c.calendar

MinSupportedDateTime : 1/1/0001 12:00:00 AM
MaxSupportedDateTime : 12/31/9999 11:59:59 PM
AlgorithmType        : SolarCalendar
CalendarType         : Localized
Eras                 : {1}
TwoDigitYearMax      : 2029
IsReadOnly           : False

C:\PS> $c.datetimeformat

AMDesignator                     : AM
Calendar                         : System.Globalization.GregorianCalendar
DateSeparator                    : /
FirstDayOfWeek                   : Sunday
CalendarWeekRule                 : FirstDay
FullDateTimePattern              : dddd, MMMM dd, yyyy h:mm:ss tt
LongDatePattern                  : dddd, MMMM dd, yyyy
LongTimePattern                  : h:mm:ss tt
MonthDayPattern                  : MMMM dd
PMDesignator                     : PM
RFC1123Pattern                   : ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
ShortDatePattern                 : M/d/yyyy
ShortTimePattern                 : h:mm tt
SortableDateTimePattern          : yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator                    : :
UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z'
YearMonthPattern                 : MMMM, yyyy
AbbreviatedDayNames              : {Sun, Mon, Tue, Wed...}
ShortestDayNames                 : {Su, Mo, Tu, We...}
DayNames                         : {Sunday, Monday, Tuesday, Wednesday...}
AbbreviatedMonthNames            : {Jan, Feb, Mar, Apr...}
MonthNames                       : {January, February, March, April...}
IsReadOnly                       : False
NativeCalendarName               : Gregorian Calendar
AbbreviatedMonthGenitiveNames    : {Jan, Feb, Mar, Apr...}
MonthGenitiveNames               : {January, February, March, April...}

C:\PS> $c.datetimeformat.firstdayofweek
Sunday

Description
-----------
This example demonstrates the vast amount of data in the culture object. It shows how to display the properties and sub-properties of the object.

The first command uses the Get-Culture cmdlet to get the current culture settings on the computer. It stores the resulting culture object in the $c variable.

The second command displays all of the properties of the culture object. It uses a pipeline operator (|) to send the culture object in $c to the Format-List cmdlet. It uses the Property parameter to display all (*) properties of the object. (This command can be abbreviated as "$c | fl *".)

The remaining commands explore the properties of the culture object by using dot notation to display the values of the object properties. You can use this notation to display the value of any property of the object.

The third command uses dot notation to display the value of the Calendar property of the culture object.

The fourth command uses dot notation to display the value of the DataTimeFormat property of the culture object.

Many object properties have properties. The fifth command uses dot notation to display the value of the FirstDayOfWeek property of the DateTimeFormat property.


Get-Date

Gets the current date and time.

Syntax

Get-Date [-Format <string>] [[-Date] <DateTime>] [-Day <int>] [-DisplayHint {<Date> | <Time> | <DateTime>}] [-Hour <int>] [-Minute <int>] [-Month <int>] [-Second <int>] [-Year <int>] [<CommonParameters>]

Get-Date [-UFormat <string>] [[-Date] <DateTime>] [-Day <int>] [-DisplayHint {<Date> | <Time> | <DateTime>}] [-Hour <int>] [-Minute <int>] [-Month <int>] [-Second <int>] [-Year <int>] [<CommonParameters>]

Description

The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. It can format the date and time in several Windows and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs.

Parameters

-Date <DateTime>

Specifies a date and time. By default, Get-Date gets the current system date and time.

Type the date in a format that is standard for the system locale, such as dd-MM-yyyy (German [Germany]) or MM/dd/yyyy (English [United States]).

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Day <int>

Specifies the day of the month that is displayed. Enter a value from 1 to 31. This value is displayed instead of the current day.

If you specify a value that is greater than the number of days in the month, Windows PowerShell adds the number of days to the month and displays the result. For example, "get-date -month 2 -day 31" displays "March 3", not "February 31".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DisplayHint <DisplayHintType>

Determines which elements of the date and time are displayed.

Valid values are:

-- Date: displays only the date

-- Time: displays only the time

-- DateTime: displays the date and time

DateTime is the default.

This parameter does not affect the DateTime object that Get-Date retrieves.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Format <string>

Displays the date and time in the Microsoft .NET Framework format indicated by the format specifier. Enter a format specifier. For a list of available format specifiers, see "DateTimeFormatInfo Class" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143638.

When you use the Format parameter, Windows PowerShell retrieves only the properties of the DateTime object that it needs to display the date in the format that you specify. As a result, some of the properties and methods of DateTime objects might not be available.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Hour <int>

Specifies the hour that is displayed. Enter a value from 1 to 23. This value is displayed instead of the current hour.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Minute <int>

Specifies the minute that is displayed. Enter a value from 1 to 59. This value is displayed instead of the current minute.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Month <int>

Specifies the month that is displayed. Enter a value from 1 to 12. This value is displayed instead of the current month.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Second <int>

Specifies the second that is displayed. Enter a value from 1 to 59. This value is displayed instead of the current second.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UFormat <string>

Displays the date and time in UNIX format. For a list of the format specifiers, see the Notes section.

When you use the UFormat parameter, Windows PowerShell retrieves only the properties of the DateTime object that it needs to display the date in the format that you specify. As a result, some of the properties and methods of DateTime objects might not be available.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Year <int>

Specifies the year that is displayed. Enter a value from 1 to 9999. This value is displayed instead of the current year.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.DateTime or System.String When you use the Format or UFormat parameters, the output object is System.String.

Notes

By default, the date-time is displayed in long-date and long-time formats for the system locale.

When you pipe a date to cmdlets that expect string input, such as Add-Content, Windows PowerShell converts the DateTime object to a string before adding it to the file. The default ToString() format is short date and long time. To specify an alternate format, use the Format or UFormat parameters of Get-Date.

Uformat Values:

The following are the values of the UFormat parameter. The format for the command is:

get-date -uformat %<value>

For example,

get-date -uformat %d

Date-Time:

Date and time - full

(default) (Friday, June 16, 2006 10:31:27 AM)

c Date and time - abbreviated (Fri Jun 16 10:31:27 2006)

Date:

D Date in mm/dd/yy format (06/14/06)

x Date in standard format for locale (09/12/07 for English-US)

Year:

C Century (20 for 2006)

Y Year in 4-digit format (2006)

y Year in 2-digit format (06)

G Same as 'Y'

g Same as 'y'

Month:

b Month name - abbreviated (Jan)

B Month name - full (January)

h Same as 'b'

m Month number (06)

Week:

W Week of the year (00-52)

V Week of the year (01-53)

U Same as 'W'

Day:

a Day of the week - abbreviated name (Mon)

A Day of the week - full name (Monday)

u Day of the week - number (Monday = 1)

d Day of the month - 2 digits (05)

e Day of the month - digit preceded by a space ( 5)

j Day of the year - (1-366)

w Same as 'u'

Time:

p AM or PM

r Time in 12-hour format (09:15:36 AM)

R Time in 24-hour format - no seconds (17:45)

T Time in 24 hour format (17:45:52)

X Same as 'T'

Z Time zone offset from Universal Time Coordinate (UTC) (-07)

Hour:

H Hour in 24-hour format (17)

I Hour in 12 hour format (05)

k Same as 'H'

l Same as 'I' (Upper-case I = Lower-case L)

Minutes & Seconds:

M Minutes (35)

S Seconds (05)

s Seconds elapsed since January 1, 1970 00:00:00 (1150451174.95705)

Special Characters:

n newline character (\n)

t Tab character (\t)

Example 1

C:\PS>get-date -DisplayHint date

Tuesday, June 13, 2006

Description
-----------
This command retrieves a DateTime object, but it displays only the date. It uses the DisplayHint parameter to indicate that only the date is to be displayed.

Example 2

C:\PS>get-date -format g

6/13/2006 12:43 PM

Description
-----------
This command retrieves the current date and time and formats it in short-date and short-time format. It uses the .NET Framework "g" format specifier (General [short date and short time]) to specify the format.

Example 3

C:\PS>get-date -uformat "%Y / %m / %d / %A / %Z"

2006 / 06 / 13 / Tuesday / -07

Description
-----------
This command retrieves the current date and time and formats it as specified by the command. In this case, the format includes the full year (%Y), the two-digit numeric month (%m), the date (%d), the full day of the week (%A), and the offset from UTC ("Zulu").

Example 4

C:\PS>(get-date -year 2000 -month 12 -day 31).dayofyear

366

Description
-----------
This command displays the day of the year for the current date. For example, December 31 is the 365th day of 2006, but it is the 366th day of 2000.

Example 5

C:\PS>$a = get-date

C:\PS> $a.IsDaylightSavingTime()

True

Description
-----------
These commands tell you whether the current date and time are adjusted for daylight savings time in the current locale.

The first command creates a variable named $a and then assigns the object retrieved by Get-Date to the $a variable. Then, it uses the IsDaylightSavingTime method on the object in $a.

To see the properties and methods of the DateTime object, type:
 "get-date | get-member".

Example 6

C:\PS>$a = get-date

C:\PS> $a.ToUniversalTime()

Tuesday, June 13, 2006 8:09:19 PM

Description
-----------
These commands convert the current date and time to UTC time.

The first command creates a variable named $a and then assigns the object retrieved by Get-Date to the $a variable. Then, it uses the ToUniversalTime method on the object in $a.

Example 7

C:\PS>$a = get-wmiobject win32_bios -computer server01

$a | format-list -property Name, @{Label="BIOS Age"; `
Expression={(get-date) - $_.ConvertToDateTime($_.ReleaseDate)}}

Name     : Default System BIOS
BIOS Age : 1345.17:31:07.1091047

Description
-----------
Windows Management Instrumentation (WMI) uses a different date-time object than the .NET Framework date-time object that Get-Date returns. To use date-time information from WMI in a command with date-time information from Get-Date, you have to use the ConvertToDateTime method to convert WMI CIM_DATETIME objects to .NET Framework DateTime objects.

The commands in this example display the name and age of the BIOS on a remote computer, Server01.

The first command uses the Get-WmiObject cmdlet to get an instance of the Win32_BIOS class on Server01 and then stores it in the $a variable.

The second command uses the pipeline operator (|) to send the WMI object stored in $a to the Format-List cmdlet. The Property parameter of Format-List is used to specify two properties to display in the list, "Name" and "BIOS Age". The "BIOS Age" property is specified in a hash table. The table includes the Label key, which specifies the name of the property, and the Expression key, which contains the expression that calculates the BIOS age. The expression uses the ConvertToDateTime method to convert each instance of ReleaseDate to a .NET Framework DateTime object. Then, the value is subtracted from the value of the Get-Date cmdlet, which, without parameters, gets the current date.

The backtick character (`) is the line continuation character in Windows PowerShell.

Example 8

C:\PS>get-date

Tuesday, June 13, 2006 12:43:42 PM

Description
-----------
This command gets a DateTime object and displays the current date and time in the long date and long time formats for the system locale, as though you typed "get-date -format F".

Example 9

C:\PS>get-date

C:\PS> Tuesday, September 26, 2006 11:25:31 AM

c:\PS>(get-date).ToString()
9/26/2006 11:25:31 AM

C:\PS>get-date | add-content test.txt
# Adds 9/26/2006 11:25:31 AM

C:\PS>get-date -format F | add-content test.txt
# Adds Tuesday, September 26, 2006 11:25:31 AM

Description
-----------
These commands demonstrate how to use Get-Date with Add-Content and other cmdlets that convert the DateTime object that Get-Date generates to a string.

The first command shows that the default display from a "get-date" command is in long-date and long-time format.

The second command shows that the default display from the ToString() method of the DateTime object is in short-date and short-time format.

The third command uses a pipeline operator to send the DateTime object to the Add-Content cmdlet, which adds the content to the Test.txt file. Because Add-Content uses the ToString() method of the DateTime object, the date that is added is in short-date and short-time format.

The fourth command uses the Format parameter of Get-Date to specify the format. When you use the Format or UFormat parameters, Get-Date generates a string, not a DateTime object. Then, when you send the string to Add-Content, it adds the string to the Test.txt file without changing it.

See Also

  • Set-Date
  • New-TimeSpan


Get-Event

Gets the events in the event queue.

Syntax

Get-Event [-EventIdentifier] <int> [<CommonParameters>]

Get-Event [[-SourceIdentifier] <string>] [<CommonParameters>]

Description

The Get-Event cmdlet gets events in the Windows PowerShell event queue for the current session. You can get all events or use the EventIdentifier or SourceIdentifier parameters to specify the events.

When an event occurs, it is added to the event queue. The event queue includes events for which you have registered, events created by using the New-Event cmdlet, and the event that is raised when Windows PowerShell exits. You can use Get-Event or Wait-Event to get the events.

This cmdlet does not get events from the Event Viewer logs. To get those events, use Get-WinEvent or Get-EventLog.

Parameters

-EventIdentifier <int>

Gets only the events with the specified event identifier.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-SourceIdentifier <string>

Gets only events with the specified source identifier. The default is all events in the event queue. Wildcards are not permitted.

Required? | false
Position? | 1
Default Value | All events
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.PSEventArgs Get-Event returns a PSEventArgs object for each event. To see a description of this object, type "get-help get-event -full" and see the Notes section of the help topic.

Notes

Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

The Get-Event cmdlet returns a PSEventArgs object (System.Management.Automation.PSEventArgs) with the following properties.

-- ComputerName: The name of the computer on which the event occurred. This property value is populated only when the event is forwarded from a remote computer.

-- RunspaceId: A GUID that uniquely identifies the session in which the event occurred. This property value is populated only when the event is forwarded from a remote computer.

-- EventIdentifier: An integer (Int32) that uniquely identifies the event notification in the current session.

-- Sender: The object that generated the event. In the value of the Action parameter, the $Sender automatic variable contains the sender object.

-- SourceEventArgs: The first parameter that derives from EventArgs, if it exists. For example, in a timer elapsed event in which the signature has the form "Object sender, Timers.ElapsedEventArgs e", the SourceEventArgs property would contain the Timers.ElapsedEventArgs. In the value of the Action parameter, the $SourceEventArgs automatic variable contains this value.

-- SourceArgs: All parameters of the original event signature. For a standard event signature, $args[0] represents the sender, and $args[1] represents the SourceEventArgs. In the value of the Action parameter, the $SourceArgs automatic variable contains this value.

-- SourceIdentifier: A string that identifies the event subscription. In the value of the Action parameter, the SourceIdentifier property of the $Event automatic variable contains this value.

-- TimeGenerated: A DateTime object that represents the time at which the event was generated. In the value of the Action parameter, the TimeGenerated property of the $Event automatic variable contains this value.

--MessageData: Data associated with the event subscription. Users specify this data when they register an event. In the value of the Action parameter, the MessageData property of the $Event automatic variable contains this value.

Example 1

C:\PS>get-event

This command gets all events in the event queue.

Example 2

C:\PS>get-event -sourceIdentifier "PowerShell.ProcessCreated"

This command gets events in which the value of the SourceIdentifier property is "PowerShell.ProcessCreated".

Example 3

C:\PS>$events = get-event

C:\PS> $events[0] | format-list -property *

ComputerName     :
RunspaceId       : c2153740-256d-46c0-a57c-b805917d1b7b
EventIdentifier  : 1
Sender           : System.Management.ManagementEventWatcher
SourceEventArgs  : System.Management.EventArrivedEventArgs
SourceArgs       : {System.Management.ManagementEventWatcher, System.Management.EventArrivedEventArgs}
SourceIdentifier : ProcessStarted
TimeGenerated    : 11/13/2008 12:09:32 PM
MessageData      :

C:\PS> get-event | where {$_.TimeGenerated -ge "11/13/2008 12:15:00 PM"}

ComputerName     :
RunspaceId       : c2153740-256d-46c0-a57c-b8059325d1a0
EventIdentifier  : 1
Sender           : System.Management.ManagementEventWatcher
SourceEventArgs  : System.Management.EventArrivedEventArgs
SourceArgs       : {System.Management.ManagementEventWatcher, System.Management.EventArrivedEventArgs}
SourceIdentifier : ProcessStarted
TimeGenerated    : 11/13/2008 12:15:00 PM
MessageData      :

Description
-----------
This example shows how to get events by using properties other than SourceIdentifier.

The first command gets all events in the event queue and saves them in the $events variable.

The second command uses array notation to get the first (0-index) event in the array in the $events variable. The command uses a pipeline operator (|) to send the event to the Format-List command, which displays all properties of the event in a list. This allows you to examine the properties of the event object.

The third command shows how to use the Where-Object cmdlet to get an event
based on the time that it was generated.

Example 4

C:\PS>get-event -eventIdentifier 2

This command gets the event with an event identifier of 2.

See Also

  • Register-ObjectEvent
  • Register-EngineEvent
  • Register-WmiEvent
  • Unregister-Event
  • New-Event
  • Remove-Event
  • Wait-Event


Get-EventLog

Gets the events in an event log, or a list of the event logs, on the local or remote computers.

Syntax

Get-EventLog [-AsString] [-ComputerName <string[]>] [-List] [<CommonParameters>]

Get-EventLog [-LogName] <string> [[-InstanceId] <Int64[]>] [-After <DateTime>] [-AsBaseObject] [-Before <DateTime>] [-ComputerName <string[]>] [-EntryType <string[]>] [-Index <Int32[]>] [-Message <string>] [-Newest <int>] [-Source <string[]>] [-UserName <string[]>] [<CommonParameters>]

Description

The Get-EventLog cmdlet gets events and event logs on the local and remote computers.

Use the parameters of Get-EventLog to search for events by using their property values. Get-EventLog gets only the events that match all of the specified property values.

The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.

Parameters

-After <DateTime>

Gets only the events that occur after the specified date and time. Enter a DateTime object, such as the one returned by the Get-Date cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsBaseObject

Returns a standard System.Diagnostics.EventLogEntry object for each event. Without this parameter, Get-EventLog returns an extended PSObject object with additional EventLogName, Source, and InstanceId properties.

To see the effect of this parameter, pipe the events to the Get-Member cmdlet and examine the TypeName value in the result.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsString

Returns the output as strings, instead of objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Before <DateTime>

Gets only the events that occur before the specified date and time. Enter a DateTime object, such as the one returned by the Get-Date cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Specifies a remote computer. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-EventLog even if your computer is not configured to run remote commands.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-EntryType <string[]>

Gets only events with the specified entry type. Valid values are Error, Information, FailureAudit, SuccessAudit, and Warning. The default is all events.

Required? | false
Position? | named
Default Value | All events
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Index <Int32[]>

Gets only events with the specified index values.

Required? | false
Position? | named
Default Value | All events
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InstanceId <Int64[]>

Gets only events with the specified instance IDs.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-List

Gets a list of event logs on the computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LogName <string>

Specifies the event log. Enter the log name (the value of the Log property; not the LogDisplayName) of one event log. Wildcard characters are not permitted. This parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Message <string>

Gets events that have the specified string in their messages. You can use this property to search for messages that contain certain words or phrases. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Newest <int>

Specifies the maximum number of events retrieved. Get-EventLog gets the specified number of events, beginning with the newest event in the log.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Source <string[]>

Gets events that were written to the log by the specified sources. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-UserName <string[]>

Gets only the events that are associated with the specified user names. Enter names or name patterns, such as User01, User*, or Domain01\User*. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None. You cannot pipe input to this cmdlet.
Outputs | System.Diagnostics.EventLogEntry. System.Diagnostics.EventLog. System.String If the LogName parameter is specified, the output is a collection of EventLogEntry objects (System.Diagnostics.EventLogEntry). If only the List parameter is specified, the output is a collection of EventLog objects (System.Diagnostics.EventLog). If both the List and AsString parameters are specified, the output is a collection of Strings (System.String).

Example 1

C:\PS>get-eventlog -list

This command displays information about the event logs on the computer.

Example 2

C:\PS>get-eventlog -newest 5 -logname application

This command displays the five most recent entries in the Application event log.

Example 3

C:\PS>$events = get-eventlog -logname system -newest 1000

C:\PS> $events | group-object -property source -noelement | sort-object -property count -descending

Count Name
----- ----
   75 Service Control Manager
   12 Print
    6 UmrdpService
    2 DnsApi
    2 DCOM
    1 Dhcp
    1 TermDD
    1 volsnap

Description
-----------
This example shows how to find all of the sources that are represented in the 1000 most recent entries in the System event log.

The first command gets the 1,000 most recent entries from the System event log and stores them in the $events variable.

The second command uses a pipeline operator (|) to send the events in $events to the Group-Object cmdlet, which groups the entries by the value of the Source property. The command uses a second pipeline operator to send the grouped events to the Sort-Object cmdlet, which sorts them in descending order, so the most frequently appearing source is listed first.

Source is just property of event log entries. To see all of the properties of an event log entry, pipe the events to the Get-Member cmdlet.

Example 4

C:\PS>get-eventlog -logname System -EntryType Error

This command gets only error events from the System event log.

Example 5

C:\PS>get-eventlog -logname System -instanceID 3221235481 -Source "DCOM"

This command gets events from the System log that have an InstanceID of 3221235481 and a Source value of "DCOM."

Example 6

C:\PS>get-eventlog -logname "Windows PowerShell" -computername localhost, Server01, Server02

This command gets the events from the "Windows PowerShell" event log on three computers, Server01, Server02, and the local computer, known as "localhost".

Example 7

C:\PS>get-eventlog -logname "Windows PowerShell" -message "*failed*"

This command gets all the events in the Windows PowerShell event log that have a message value that includes the word "failed".

Example 8

C:\PS>$a = get-eventlog -log System -newest 1

C:\PS> $a | format-list -property *

EventID            : 7036
MachineName        : Server01
Data               : {}
Index              : 10238
Category           : (0)
CategoryNumber     : 0
EntryType          : Information
Message            : The description for Event ID
Source             : Service Control Manager
ReplacementStrings : {WinHTTP Web Proxy Auto-Disco
InstanceId         : 1073748860
TimeGenerated      : 4/11/2008 9:56:05 PM
TimeWritten        : 4/11/2008 9:56:05 PM
UserName           :
Site               :
Container          :

Description
-----------
This example shows how to display all of the property values of an event.

The first command gets the newest event from the System event log and saves it in the $a variable.

The second command uses a pipeline operator (|) to send the event in $a to the Format-List command, which displays all (*) of the event properties.

Example 9

C:\PS>get-eventlog -log application -source outlook | where {$_.eventID -eq 34}

This command gets events in the Application event log where the source is Outlook and the event ID is 34. Even though Get-EventLog does not have an EventID parameter, you can use the Where-Object cmdlet to select events based on the value of any event property.

Example 10

C:\PS>get-eventlog -log system -username NT* | group-object -property username -noelement | format-table Count, Name -auto

Count Name
----- ----
 6031 NT AUTHORITY\SYSTEM
   42 NT AUTHORITY\LOCAL SERVICE
    4 NT AUTHORITY\NETWORK SERVICE

Description
-----------
This command returns the events in the system log grouped by the value of  their UserName property. The Get-EventLog command uses the UserName parameter to get only events in which the user name begins with "NT*".

Example 11

C:\PS>$May31 = get-date 5/31/08

C:\PS> $July1 = get-date 7/01/08

C:\PS> get-eventlog -log "Windows PowerShell" -entrytype Error -after $may31 -before $july1

This command gets all of the errors in the Windows PowerShell event log that occurred in June 2008.

See Also

  • Get-WinEvent
  • Clear-EventLog
  • Limit-EventLog
  • New-EventLog
  • Remove-EventLog
  • Show-Eventlog
  • Write-EventLog
  • Get-WinEvent


Get-EventSubscriber

Gets the event subscribers in the current session.

Syntax

Get-EventSubscriber [-SubscriptionId] <int> [[-SourceIdentifier] <string>] [-Force] [<CommonParameters>]

Description

The Get-EventSubscriber cmdlet gets the event subscribers in the current session.

When you subscribe to an event by using a Register event cmdlet, an event subscriber is added to your Windows PowerShell session, and the events to which you subscribed are added to your event queue whenever they are raised. To cancel an event subscription, delete the event subscriber by using the Unregister-Event cmdlet.

Parameters

-Force

Gets all event subscribers, including subscribers for events that are hidden by using the SupportEvent parameter of Register-ObjectEvent, Register-WmiEvent, and Register-EngineEvent.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SourceIdentifier <string>

Gets only the event subscribers with the specified SourceIdentifier property value. By default, Get-EventSubscriber gets all event subscribers in the session. Wildcards are not permitted. This parameter is case-sensitive.

Required? | false
Position? | 1
Default Value | All event subscribers
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-SubscriptionId <int>

Gets only the specified subscription identifier. By default, Get-EventSubscriber gets all event subscribers in the session.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.PSEventSubscriber Get-EventSubscriber returns an object that represents each event subscriber.

Notes

The New-Event cmdlet, which creates a custom event, does not generate a subscriber. Therefore, the Get-EventSubscriber cmdlet will not find a subscriber object for these events. However, if you use the Register-EngineEvent cmdlet to subscribe to a custom event (in order to forward the event or to specify an action), Get-EventSubscriber will find the subscriber that Register-EngineEvent generates.

Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

Example 1

C:\PS>$timer = New-Object Timers.Timer

C:\PS> $timer | Get-Member -Type Event

C:\PS> Register-ObjectEvent -inputObject $timer -EventName Elapsed -SourceIdentifier Timer.Elapsed

C:\PS> Get-EventSubscriber

C:\PS> $timer = New-Object Timers.Timer

C:\PS> $timer | Get-Member -Type Event

   TypeName: System.Timers.Timer

Name     MemberType Definition
----     ---------- ----------
Disposed Event      System.EventHandler Disposed(System.Object, System.EventArgs)
Elapsed  Event      System.Timers.ElapsedEventHandler Elapsed(System.Object, System.Timers.ElapsedEventArgs)

C:\PS> Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier Timer.Elapsed

C:\PS> Get-EventSubscriber

SubscriptionId   : 4
SourceObject     : System.Timers.Timer
EventName        : Elapsed
SourceIdentifier : Timer.Elapsed
Action           :
HandlerDelegate  :
SupportEvent     : False
ForwardEvent     : False

Description
-----------
This example uses a Get-EventSubscriber command to get the event subscriber for a timer event.

The first command uses the New-Object cmdlet to create an instance of a timer object. It saves the new timer object in the $timer variable.

The second command uses the Get-Member cmdlet to display the events that are available for timer objects. The command uses the Type parameter of the Get-Member cmdlet with a value of Event.

The third command uses the Register-ObjectEvent cmdlet to register for the Elapsed event on the timer object.

The fourth command uses the Get-EventSubscriber cmdlet to get the event subscriber for the Elapsed event.

Example 2

C:\PS>$timer  = New-Object Timers.Timer

C:\PS> $timer.Interval = 500

C:\PS> Register-ObjectEvent -inputObject $timer -eventName Elapsed -sourceIdentifier Timer.Random -Action { $random = Get-Random -Min 0 -Max 100 }

Id  Name           State      HasMoreData  Location  Command
--  ----           -----      -----------  --------  -------
3   Timer.Random   NotStarted False                  $random = Get-Random ...

C:\PS> $timer.Enabled = $true

C:\PS> $subscriber = Get-EventSubcriber -sourceIdentifer Timer.Random

C:\PS> ($subscriber.action).gettype().fullname
PSEventJob

C:\PS> $subscriber.action | format-list -property *

State         : Running
Module        : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0
StatusMessage :
HasMoreData   : True
Location      :
Command       : $random = Get-Random -Min 0 -Max 100
JobStateInfo  : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : 88944290-133d-4b44-8752-f901bd8012e2
Id            : 1
Name          : Timer.Random
ChildJobs     : {}
...

C:\PS> & $subscriber.action.module {$random}
96

C:\PS> & $subscriber.action.module {$random}
23

Description
-----------
This example shows how to use the dynamic module in the PSEventJob object in the Action property of the event subscriber.

The first command uses the New-Object cmdlet to create a timer object. The second command sets the interval of the timer to 500 (milliseconds).

The third command uses the Register-ObjectEvent cmdlet to register the Elapsed event of the timer object. The command includes an action that handles the event. Whenever the timer interval elapses, an event is raised and the commands in the action run. In this case, the Get-Random cmdlet generates a random number between 0 and 100 and saves it in the $random variable. The source identifier of the event is Timer.Random.

When you use an Action parameter in a Register-ObjectEvent command, the command returns a PSEventJob object that represents the action.

The fourth command enables the timer.

The fifth command uses the Get-EventSubscriber cmdlet to get the event subscriber of the Timer.Random event. It saves the event subscriber object in the $subscriber variable.

The sixth command shows that the Action property of the event subscriber object contains a PSEventJob object. In fact, it contains the same PSEventJob object that the Register-ObjectEvent command returned.

The seventh command uses the Format-List cmdlet to display all of the properties of the PSEventJob object in the Action property in a list. The result reveal that the PSEventJob object has a Module property that contains a dynamic script module that implements the action.

The remaining commands use the call operator (&) to invoke the command in the module and display the value of the $random variable. You can use the call operator to invoke any command in a module, including commands that are not exported. In this case, the commands show the random number that is being generated when the Elapsed event occurs.

For more information about modules, see about_Modules.

See Also

  • Register-ObjectEvent
  • Register-EngineEvent
  • Register-WmiEvent
  • Unregister-Event
  • Get-Event
  • New-Event
  • Remove-Event
  • Wait-Event


Get-ExecutionPolicy

Gets the execution policies for the current session.

Syntax

Get-ExecutionPolicy [[-Scope] {<Process> | <CurrentUser> | <LocalMachine> | <UserPolicy> | <MachinePolicy>}] [-List] [<CommonParameters>]

Description

The Get-ExecutionPolicy cmdlet gets the execution policies for the current session.

The execution policy is determined by execution policies that you set by using Set-ExecutionPolicy and the Group Policy settings for the Windows PowerShell execution policy. The default value is "Restricted."

Without parameters, Get-ExecutionPolicy gets the execution policy that is effective in the session. You can use the List parameter to get all execution policies that affect the session or the Scope parameter to get the execution policy for a particular scope.

For more information, see about_Execution_Policies.

Parameters

-List

Gets all execution policy values for the session listed in precedence order. By default, Get-ExecutionPolicy gets only the effective execution policy.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Scope <ExecutionPolicyScope>

Gets the execution policy in the specified scope. By default, Get-ExecutionPolicy gets the effective execution policy for the current session.

Valid values are:

-- MachinePolicy: The execution policy set by a Group Policy for all users of the computer.

-- UserPolicy: The execution policy set by a Group Policy for the current user of the computer.

-- Process: The execution policy that is set for the current Windows PowerShell process.

-- CurrentUser: The execution policy that is set for the current user.

-- LocalMachine: The execution policy that is set for all users of the computer.

Required? | false
Position? | 1
Default Value | Effective execution policy
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | Microsoft.PowerShell.ExecutionPolicy Get-ExecutionPolicy returns an object for each execution policy that it gets.

Notes

You cannot use Get-ExecutionPolicy to get particular execution policies set for a particular scope or to get the execution policy set by a Group Policy. Get-ExecutionPolicy only gets the effective execution policy that results from applying all precedence rules.

The execution policy is part of the security strategy of Windows PowerShell. It determines whether you can load configuration files (including your Windows PowerShell profile) and run scripts, and it determines which scripts, if any, must be digitally signed before they will run.

The effective execution policy is determined by the policies that you set by using Set-ExecutionPolicy and the "Turn on Script Execution" group policies for computers and users. The precedence order is Computer Group Policy > User Group Policy > Process (session) execution policy > User execution policy > Computer execution policy.

For more information about Windows PowerShell execution policy, including definitions of the Windows PowerShell policies, see about_Execution_Policies.

Example 1

C:\PS>get-executionpolicy

Restricted

Description
-----------
This command gets the current execution policy for the shell.

Example 2

C:\PS>set-executionpolicy RemoteSigned; get-executionPolicy

RemoteSigned

Description
-----------
These commands set a new user preference for the shell execution policy and then display the effective execution policy. The commands are separated by a semicolon (;). In this example, because there is no Group Policy setting, the user preference is the effective policy for the shell.

Example 3

C:\PS>get-executionpolicy -list

Scope  ExecutionPolicy
        -----  ---------------
MachinePolicy  Undefined
   UserPolicy  Undefined
      Process  Undefined
  CurrentUser  AllSigned
 LocalMachine  RemoteSigned

C:\PS> get-executionpolicy
AllSigned

Description
-----------
These commands get all execution policies in the current session and the effective execution policy.

The first command gets all execution policies that affect the current session. The policies are listed in precedence order.

The second command gets only the effective execution policy, which is the one set in the CurrentUser scope.

See Also

  • Set-ExecutionPolicy
  • Get-AuthenticodeSignature
  • Set-AuthenticodeSignature
  • about_Execution_Policies
  • about_Signing


Get-FormatData

Gets the formatting data in the current session.

Syntax

Get-FormatData [[-TypeName] <string[]>] [<CommonParameters>]

Description

The Get-FormatData cmdlet gets the formatting data in the current session.

The formatting data in the session includes formatting data from Format.ps1xml formatting files (such as those in the $pshome directory), formatting data for modules that you import into the session, and formatting data for commands that you import into your session by using the Import-PSSession cmdlet.

You can use this cmdlet to examine the formatting data. Then, you can use the Export-FormatData cmdlet to serialize the objects (convert them to XML) and save them in Format.ps1xml files.

For more information about formatting files in Windows PowerShell, see about_Format.ps1xml.

Parameters

-TypeName <string[]>

Gets only the formatting data with the specified type names. Enter the type names. Wildcards are permitted.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.ExtendedTypeDefinition

Example 1

C:\PS>get-formatdata

This command gets all the formatting data in the session.

Example 2

C:\PS>get-formatdata -typename Microsoft.Wsman*

This command gets the formatting data items whose names begin with "Microsoft.Wsman".

Example 3

C:\PS>$f = get-formatdata -typename helpinfoshort

C:\PS> $f

TypeName        FormatViewDefinition
--------        --------------------
HelpInfoShort   {help , TableControl}

C:\PS> $f.FormatViewDefinition[0].control

Headers                                                                    Rows
-------                                                                    ----
{System.Management.Automation.TableControlColumnHeader, System.Manageme... {System.Management.Automation.TableControlRow}

C:\PS> $f.FormatViewDefinition[0].control.headers

Label         Alignment      Width
-----         ---------      -----
Name          Left           33
Category      Left           9
              Undefined      0

Description
-----------
This example shows how to get a formatting data object and examine its properties.

Example 4

C:\PS>$a = get-formatdata

C:\PS> import-module bitstransfer
C:\PS> $b = get-formatdata
C:\PS> compare-object $a $b

InputObject                                                SideIndicator
-----------                                                -------------
Microsoft.BackgroundIntelligentTransfer.Management.BitsJob =>

C:\PS> get-formatdata *bits* | export-formatdata -filepath c:\test\bits.format.ps1xml

C:\PS> get-content c:\test\bits.format.ps1xml

<?xml version="1.0" encoding="utf-8"?><Configuration><ViewDefinitions>
<View><Name>Microsoft.BackgroundIntelligentTransfer.Management.BitsJob</Name>
...

Description
-----------
This example shows how to use Get-FormatData and Export-FormatData to export the formatting data that is added by a module.

The first four commands use the Get-FormatData, Import-Module, and Compare-Object cmdlets to identify the format type that the BitsTransfer module adds to the session.

The fifth command uses the Get-FormatData cmdlet to get the format type that the BitsTransfer module adds. It uses a pipeline operator (|) to send the format type object to the Export-FormatData cmdlet, which converts it back to XML and saves it in the specified format.ps1xml file.

The final command shows an excerpt of the format.ps1xml file content.

See Also

  • Export-FormatData
  • Update-FormatData


Get-Help

Displays information about Windows PowerShell commands and concepts.

Syntax

Get-Help [-Full] [[-Name] <string>] [-Category <string[]>] [-Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role <string[]>] [<CommonParameters>]

Get-Help [-Detailed] [[-Name] <string>] [-Category <string[]>] [-Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role <string[]>] [<CommonParameters>]

Get-Help [-Examples] [[-Name] <string>] [-Category <string[]>] [-Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role <string[]>] [<CommonParameters>]

Get-Help [-Parameter <string>] [[-Name] <string>] [-Category <string[]>] [-Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role <string[]>] [<CommonParameters>]

Description

The Get-Help cmdlet displays information about Windows PowerShell concepts and commands, including cmdlets, providers, functions and scripts. To get a list of all cmdlet help topic titles, type "get-help *".

If you type "Get-Help" followed by the exact name of a help topic, or by a word unique to a help topic, Get-Help displays the topic contents. If you enter a word or word pattern that appears in several help topic titles, Get-Help displays a list of the matching titles. If you enter a word that does not appear in any help topic titles, Get-Help displays a list of topics that include that word in their contents.

In addition to "get-help", you can also type "help" or "man", which displays one screen of text at a time, or "<cmdlet-name> -?", which is identical to Get-Help but works only for cmdlets.

You can display the entire help file or selected parts of the file, such as the syntax, parameters, or examples. You can also use the Online parameter to display an online version of a help file in your Internet browser. These parameters have no effect on conceptual help topics.

Conceptual help topics in Windows PowerShell begin with "about_", such as "about_Comparison_Operators". To see all "about_" topics, type "get-help about_*". To see a particular topic, type "get-help about_<topic-name>", such as "get-help about_Comparison_Operators".

Parameters

-Category <string[]>

Displays help for items in the specified category. Valid values are Alias, Cmdlet, Provider, and HelpFile. Conceptual topics are in the HelpFile category.

Category is a property of the MamlCommandHelpInfo object that Get-Help returns. This parameter has no effect on displays of conceptual ("about_") help.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Component <string[]>

Displays a list of tools with the specified component value, such as "Exchange." Enter a component name. Wildcards are permitted.

Component is a property of the MamlCommandHelpInfo object that Get-Help returns. This parameter has no effect on displays of conceptual ("About_") help.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Detailed

Adds parameter descriptions and examples to the basic help display.

This parameter has no effect on displays of conceptual ("About_") help.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Examples

Displays only the name, synopsis, and examples. To display only the examples, type "(get-help <cmdlet-name>).examples".

This parameter has no effect on displays of conceptual ("About_") help.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Full

Displays the entire help file for a cmdlet, including parameter descriptions and attributes, examples, input and output object types, and additional notes.

This parameter has no effect on displays of conceptual ("About_") help.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Functionality <string[]>

Displays help for items with the specified functionality. Enter the functionality. Wildcards are permitted.

Functionality is a property of the MamlCommandHelpInfo object that Get-Help returns. This parameter has no effect on displays of conceptual ("About_") help.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Requests help about the specified tool or conceptual topic. Enter a cmdlet, provider, script, or function name, such as Get-Member, a conceptual topic name, such as "about_Objects", or an alias, such as "ls". Wildcards are permitted in cmdlet and provider names, but you cannot use wildcards to find the names of function help and script help topics.

To get help for a script that is not located in a path that is listed in the Path environment variable, type the path and file name of the script .

If you enter the exact name of a help topic, Get-Help displays the topic contents. If you enter a word or word pattern that appears in several help topic titles, Get-Help displays a list of the matching titles. If you enter a word that does not match any help topic titles, Get-Help displays a list of topics that include that word in their contents.

The names of conceptual topics, such as about_Objects, must be entered in English, even in non-English versions of Windows PowerShell.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Online

Displays the online version of a help topic in the default Internet browser. This parameter is valid only for cmdlet, function, and script help topics.

Get-Help uses the Internet address (Uniform Resource Identifier [URI]) that appears in the first item of the Related Links section of a cmdlet, function, or script help topic. This parameter works only when the help topic includes a URI that begins with "Http" or "Https" and an Internet browser is installed on the system.

For information about supporting this feature in help topics that you write, see about_Comment_Based_Help, and see "How to Write Cmdlet Help" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkID=123415.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Parameter <string>

Displays only the detailed descriptions of the specified parameters. Wildcards are permitted.

This parameter has no effect on displays of conceptual ("About_") help.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Gets help that explains how the cmdlet works in the specified provider path. Enter a Windows PowerShell provider path.

This parameter gets a customized version of a cmdlet help topic that explains how the cmdlet works in the specified Windows PowerShell provider path. This parameter is effective only for help about a provider cmdlet and only when the provider includes a custom version of the provider cmdlet help topic.

To see the custom cmdlet help for a provider path, go to the provider path location and enter a Get-Help command or, from any path location, use the Path parameter of Get-Help to specify the provider path. For more information, see about_Providers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Role <string[]>

Displays help customized for the specified user role. Enter a role. Wildcards are permitted.

Enter the role that the user plays in an organization. Some cmdlets display different text in their help files based on the value of this parameter. This parameter has no effect on help for the core cmdlets.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to this cmdlet.
Outputs | System.String or MamlCommandHelpInfo If you request a conceptual topic, Get-Help returns it as a string. If you specify the name of a cmdlet,, function, or script, it returns a MamlCommandHelpInfo object. Otherwise, Get-Help returns one of the formatted views that are specified in the Help.Format.ps1xml file in the $pshome directory.

Notes

Without parameters, "Get-Help" displays information about the Windows PowerShell help system.

The full view of help (-full) includes a table of information about the parameters. The table includes the following fields:

-- Required: Indicates whether the parameter is required (true) or optional (false).

-- Position: Indicates whether the parameter is named or positional (numbered). Positional parameters must appear in a specified place in the command.

-- "Named" indicates that the parameter name is required, but that the parameter can appear anywhere in the command.

-- <Number> indicates that the parameter name is optional, but when the name is omitted, the parameter must be in the place specified by the number. For example, "2" indicates that when the parameter name is omitted, the parameter must be the second (2) or only unnamed parameter in the command. When the parameter name is used, the parameter can appear anywhere in the command.

-- Default value: The parameter value that Windows PowerShell uses if you do not include the parameter in the command.

-- Accepts pipeline input: Indicates whether you can (true) or cannot (false) send objects to the parameter through a pipeline. "By Property Name" means that the pipelined object must have a property with the same name as the parameter name.

-- Accepts wildcard characters: Indicates whether the value of a parameter can include wildcard characters, such as * and ?.

Example 1

C:\PS>get-help

This command displays help about the Windows PowerShell help system.

Example 2

C:\PS>get-help *

This command displays a list of all help files in the Windows PowerShell help system.

Example 3

C:\PS>get-help get-alias

C:\PS>help get-alias

C:\PS>get-alias -?

These commands display basic information about the get-alias cmdlet. The "Get-Help" and "-?" commands display the information on a single page. The "Help" command displays the information one page at a time.

Example 4

C:\PS>get-help about_*

This command displays a list of the conceptual topics included in Windows PowerShell help. All of these topics begin with the characters "about_". To display a particular help file, type "get-help <topic-name>, for example, "get-help about_signing".

Example 5

C:\PS>get-help ls -detailed

This command displays detailed help for the Get-ChildItem cmdlet by specifying one of its aliases, "ls." The Detailed parameter requests the detailed view of the help file, which includes parameter descriptions and examples. To see the complete help file for a cmdlet, use the Full parameter.

Example 6

C:\PS>get-help format-string -full

This command displays the full view help for the Format-String cmdlet. The full view of help includes parameter descriptions, examples, and a table of technical details about the parameters.

Example 7

C:\PS>get-help start-service -examples

This command displays examples of using start-service in Windows PowerShell commands.

Example 8

C:\PS>get-help get-childitem -parameter f*

This command displays descriptions of the parameters of the Get-ChildItem cmdlet that begin with "f" (filter and force). For descriptions of all parameters, type "get-help get-childitem parameter*".

Example 9

C:\PS>(get-help write-output).syntax

This command displays only the syntax of the Write-Output cmdlet.

Syntax is one of many properties of help objects; others are description, details, examples, and parameters. To find all properties and methods of help objects, type "get-help <cmdlet-name> | get-member"; for example, "get-help start-service | get member".

Example 10

C:\PS>(get-help trace-command).alertset

This command displays the notes about the cmdlet. The notes are stored in the alertSet property of the help object.

The notes include conceptual information and tips for using the cmdlet. By default, the notes are displayed only when you use the Full parameter of Get-Help, but you can also display them by using the alertSet property.

Example 11

C:\PS>get-help add-member -full | out-string -stream | select-string -pattern clixml

This example shows how to search for a word in particular cmdlet help topic. This command searches for the word "clixml" in the full version of the help topic for the Add-Member cmdlet.

Because the Get-Help cmdlet generates a MamlCommandHelpInfo object, not a string, you need to use a command that transforms the help topic content into a string, such as Out-String or Out-File.

Example 12

C:\PS>get-help get-member -online

This command displays the online version of the help topic for the Get-Member cmdlet.

Example 13

C:\PS>get-help remoting

This command displays a list of topics that include the word "remoting" in their contents.

When you enter a word that does not appear in any topic title, Get-Help displays a list of topics that include that word.

Example 14

C:\PS>get-help get-item -path SQLSERVER:\DataCollection

NAME
    Get-Item

SYNOPSIS
    Gets a collection of Server objects for the local computer and any computers to which you have made a SQL Server PowerShell connection.
...

C:\PS> cd SQLSERVER:\DataCollection
C:\PS> SQLSERVER:\DataCollection> get-help get-item

NAME
    Get-Item

SYNOPSIS
    Gets a collection of Server objects for the local computer and any computers to which you have made a SQL Server PowerShell connection.
...

C:\PS> Get-Item

NAME
    Get-Item

SYNOPSIS
    Gets the item at the specified location.

...

Description
-----------
This example shows how to get help for the Get-Item cmdlet that explains how to use the cmdlet in the DataCollection node of the Windows PowerShell SQL Server provider.

The example shows two ways of getting the custom help for Get-Item.

The first command uses the Path parameter of Get-Help to specify the provider path. This command can be entered at any path location.

The second command uses the Set-Location cmdlet (alias = "cd") to go to the provider path. From that location, even without the Path parameter, the Get-Help command gets the custom help for the provider path.

The third command shows that a Get-Help command in a file system path, and without the Path parameter, gets the standard help for the Get-Item cmdlet.

Example 15

C:\PS>get-help c:\ps-test\MyScript.ps1

This command gets help for the MyScript.ps1 script. For information about writing help for your functions and scripts, see about_Comment_Based_Help.

See Also

  • about_Comment_Based_Help
  • Get-Command
  • Get-PSDrive
  • Get-Member


Get-History

Gets a list of the commands entered during the current session.

Syntax

Get-History [[-Id] <Int64[]>] [[-Count] <int>] [<CommonParameters>]

Description

The Get-History cmdlet gets the session history, that is, the list of commands entered during the current session. Windows PowerShell automatically maintains a history of each session. You can save the session history in XML or CSV format. By default, history files are saved in the home directory, but you can save the file in any location.

Parameters

-Count <int>

Displays the specified number of the most recent history entries. The default is 32. If you use both the Count and Id parameters in a command, the display ends with the command specified by the Id parameter.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Id <Int64[]>

Specifies the ID number of a command in the session history. Get-History gets only the specified command. If you use Id and Count, Get-History gets the most recent commands ending with the command specified by the Id parameter.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | Int64 You can pipe a history ID to Get-History.
Outputs | Microsoft.PowerShell.Commands.HistoryInfo Get-History returns a history object for each history item that it gets.

Notes

The session history is a list of the commands entered during the session along with the ID. The session history represents the order of execution, the status, and the start and end times of the command. As you enter each command, Windows PowerShell adds it to the history so that you can reuse it. For more information about the command history, see about_History.

You can also refer to Get-History by its built-in aliases, "h", "history", and "ghy". For more information, see about_Aliases.

Example 1

C:\PS>get-history

This command gets the 32 most recently submitted commands. The default display shows each command and its ID, which indicates the order of execution.

Example 2

C:\PS>get-history | where-object {$_.commandLine -like "*service*"}

This command gets entries from the command history that include the word, "service". The first command gets the 32 most recent entries in the session history. The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects only the commands that include "service".

Example 3

C:\PS>get-history -id 7 -count 5 | export-csv history.csv

This command gets the five most recent history entries ending with entry 7. The pipeline operator (|) passes the result to the Export-Csv cmdlet, which formats the history as comma-separated text and saves it in the History.csv file. The file includes the data that is displayed when you format the history as a list, including the status and start and end times of the command.

Example 4

C:\PS>get-history -count 1

This command gets the last (most recently entered) command in the command history. It uses the Count parameter to display just one command. By default, Get-History displays the most recent commands. This command can be abbreviated to "h -c 1" and is equivalent to pressing the up-arrow key.

Example 5

C:\PS>get-history -count $MaximumHistoryCount

This command displays all of the commands saved in the session history. By default, $MaximumHistoryCount is 64, so this command can be abbreviated as "h -c 64".

Example 6

C:\PS>get-history | format-list

This command displays all of the properties of entries in the session history. The pipeline operator (|) passes the result to the Format-List cmdlet, which displays all of the properties of each history entry, including the ID, status, and start and end times of the command.

See Also

  • about_History
  • Invoke-History
  • Add-History
  • Clear-History


Get-Host

Gets an object that represents the current host program. And, displays Windows PowerShell version and regional information by default.

Syntax

Get-Host [<CommonParameters>]

Description

The Get-Host cmdlet gets an object that represents the program that is hosting Windows PowerShell.

The default display includes the Windows PowerShell version number and the current region and language settings that the host is using, but the host object contains a wealth of information, including detailed information about the version of Windows PowerShell that is currently running and the current culture and UI culture of Windows PowerShell. You can also use this cmdlet to customize features of the host program user interface, such as the text and background colors.

Parameters

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.Internal.Host.InternalHost Get-Host returns a System.Management.Automation.Internal.Host.InternalHost object.

Notes

The $host automatic variable contains the same object that Get-Host returns, and you can use it in the same way. Similarly, the $PSCulture and $PSUICulture automatic variables contain the same objects that the CurrentCulture and CurrentUICulture properties of the host object contain. You can use these features interchangeably.

For more information, see about_Automatic_Variables.

Example 1

C:\PS>get-host

Name             : ConsoleHost
Version          : 2.0
InstanceId       : e4e0ab54-cc5e-4261-9117-4081f20ce7a2
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

Description
-----------
This command displays information about the Windows PowerShell console, which is the current host program for Windows PowerShell in this example. It includes the name of the host, the version of Windows PowerShell that is running in the host, and current culture and UI culture.

The Version, UI, CurrentCulture, CurrentUICulture, PrivateData, and Runspace properties each contain an object with very useful properties. Later examples examine these properties.

Example 2

C:\PS>$h = get-host

C:\PS> $win = $h.ui.rawui.windowsize

C:\PS> $win.height = 10

C:\PS> $win.width  = 10

C:\PS> $h.ui.rawui.set_windowsize($win)

This command resizes the Windows PowerShell window to 10 pixels by 10 pixels.

Example 3

C:\PS>(get-host).version | format-list -property *

Major         : 2
Minor         : 0
Build         : -1
Revision      : -1
MajorRevision : -1
MinorRevision : -1

Description
-----------
This command gets detailed information about the version of Windows PowerShell running in the host. You can view, but not change, these values.

The Version property of Get-Host contains a System.Version object. This command uses a pipeline operator (|) to send the version object to the Format-List cmdlet. The Format-List command uses the Property parameter with a value of all (*) to display all of the properties and property values of the version object.

Example 4

C:\PS>(get-host).currentculture | format-list -property *

Parent                         : en
LCID                           : 1033
KeyboardLayoutId               : 1033
Name                           : en-US
IetfLanguageTag                : en-US
DisplayName                    : English (United States)
NativeName                     : English (United States)
EnglishName                    : English (United States)
TwoLetterISOLanguageName       : en
ThreeLetterISOLanguageName     : eng
ThreeLetterWindowsLanguageName : ENU
CompareInfo                    : CompareInfo - 1033
TextInfo                       : TextInfo - 1033
IsNeutralCulture               : False
CultureTypes                   : SpecificCultures, InstalledWin32Cultures, FrameworkCultures
NumberFormat                   : System.Globalization.NumberFormatInfo
DateTimeFormat                 : System.Globalization.DateTimeFormatInfo
Calendar                       : System.Globalization.GregorianCalendar
OptionalCalendars              : {System.Globalization.GregorianCalendar, System.Globalization.GregorianCalendar}
UseUserOverride                : True
IsReadOnly                     : False

Description
-----------
This command gets detailed information about the current culture set for Windows PowerShell running in the host. This is the same information that is returned by the Get-Culture cmdlet.

(Similarly, the CurrentUICulture property returns the same object that Get-UICulture returns.)

The CurrentCulture property of the host object contains a  System.Globalization.CultureInfo object. This command uses a pipeline operator (|) to send the CultureInfo object to the Format-List cmdlet. The Format-List command uses the Property parameter with a value of all (*) to display all of the properties and property values of the CultureInfo object.

Example 5

C:\PS>(get-host).currentculture.DateTimeFormat | format-list -property *

AMDesignator                     : AM
Calendar                         : System.Globalization.GregorianCalendar
DateSeparator                    : /
FirstDayOfWeek                   : Sunday
CalendarWeekRule                 : FirstDay
FullDateTimePattern              : dddd, MMMM dd, yyyy h:mm:ss tt
LongDatePattern                  : dddd, MMMM dd, yyyy
LongTimePattern                  : h:mm:ss tt
MonthDayPattern                  : MMMM dd
PMDesignator                     : PM
RFC1123Pattern                   : ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
ShortDatePattern                 : M/d/yyyy
ShortTimePattern                 : h:mm tt
SortableDateTimePattern          : yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator                    : :
UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z'
YearMonthPattern                 : MMMM, yyyy
AbbreviatedDayNames              : {Sun, Mon, Tue, Wed...}
ShortestDayNames                 : {Su, Mo, Tu, We...}
DayNames                         : {Sunday, Monday, Tuesday, Wednesday...}
AbbreviatedMonthNames            : {Jan, Feb, Mar, Apr...}
MonthNames                       : {January, February, March, April...}
IsReadOnly                       : False
NativeCalendarName               : Gregorian Calendar
AbbreviatedMonthGenitiveNames    : {Jan, Feb, Mar, Apr...}
MonthGenitiveNames               : {January, February, March, April...}

Description
-----------
This command returns detailed information about the DateTimeFormat of the current culture that is being used for Windows PowerShell.

The CurrentCulture property of the host object contains a CultureInfo object that, in turn, has many useful properties. Among them, the DateTimeFormat property contains a DateTimeFormatInfo object with many useful properties.

To find the type of an object that is stored in an object property, use the Get-Member cmdlet. To display the property values of the object, use the Format-List cmdlet.

Example 6

C:\PS>(get-host).ui.rawui | format-list -property *

ForegroundColor       : DarkYellow
BackgroundColor       : DarkBlue
CursorPosition        : 0,390
WindowPosition        : 0,341
CursorSize            : 25
BufferSize            : 120,3000
WindowSize            : 120,50
MaxWindowSize         : 120,81
MaxPhysicalWindowSize : 182,81
KeyAvailable          : False
WindowTitle           : Windows PowerShell 2.0 (04/11/2008 00:08:14)

Description
-----------
This command displays the properties of the RawUI property of the host object. By changing these values, you can change the appearance of the host program.

Example 7

C:\PS>(get-host).ui.rawui.backgroundcolor = "Black"

C:\PS> cls

These commands change the background color of the Windows PowerShell console to black. The "cls" command is an alias for the Clear-Host function, which clears the screen and changes the whole screen to the new color.

This change is effective only in the current session. To change the background color of the console for all sessions, add the command to your Windows PowerShell profile.

Example 8

C:\PS>$host.privatedata.errorbackgroundcolor = "white"

This command changes the background color of error messages to white.

This command uses the $host automatic variable, which contains the host object for the current host program. Get-Host returns the same object that $host contains, so you can use them interchangeably.

This command uses the PrivateData property of $host as its ErrorBackgroundColor property. To see all of the properties of the object in the $host.privatedata property, type "$host.privatedata | format-list * ".

See Also

  • Read-Host
  • Out-Host
  • Write-Host


Get-Hotfix

Gets the hotfixes that have been applied to the local and remote computers.

Syntax

Get-HotFix [[-Id] <string[]>] [-ComputerName <string[]>] [-Credential <PSCredential>] [<CommonParameters>]

Get-HotFix [-Description <string[]>] [-ComputerName <string[]>] [-Credential <PSCredential>] [<CommonParameters>]

Description

The Get-Hotfix cmdlet gets the hotfixes that have been applied to the local computer or to remote computers by Component-Based Servicing.

Parameters

-ComputerName <string[]>

Specifies a remote computer. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name of a remote computer.

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-Hotfix even if your computer is not configured to run remote commands.

Required? | false
Position? | named
Default Value | Local computer
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | Current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Description <string[]>

Gets only hotfixes with the specified descriptions. Wildcards are permitted. The default is all hotfixes on the computer.

Required? | false
Position? | named
Default Value | All hotfixes
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Id <string[]>

Gets only hotfixes with the specified hotfix IDs. The default is all hotfixes on the computer.

Required? | false
Position? | 1
Default Value | All hotfixes
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to Get-HotFix.
Outputs | System.Management.ManagementObject#root\CIMV2\Win32_QuickFixEngineering Get-Hotfix returns objects that represent the hotfixes on the computer.

Notes

This cmdlet uses the Win32_QuickFixEngineering WMI class, which represents small system-wide updates of the operating system. Starting with Windows Vista, this class returns only the updates supplied by Component Based Servicing (CBS). It does not include updates that are supplied by Microsoft Windows Installer (MSI) or the Windows update site. For more information, see the Win32_QuickFixEngineering class topic in the Microsoft .NET Framework SDK at http://go.microsoft.com/fwlink/?LinkID=145071.

The output of this cmdlet might be different on different operating systems.

Example 1

C:\PS>get-hotfix

This command gets all hotfixes on the local computer.

Example 2

C:\PS>get-hotfix -description Security* -computername Server01, Server02 -cred Server01\admin01

This command gets all hotfixes on the Server01 and Server02 computers that have a description that begins with "Security".

Example 3

C:\PS>$a = get-content servers.txt

C:\PS> $a | foreach { if (!(get-hotfix -id KB957095 -computername $_)) { add-content $_ -path Missing-kb953631.txt }}

The commands in this example create a text file listing the names of computers that are missing a security update.

The commands use the Get-Hotfix cmdlet to get the KB957095 security update on all of the computers whose names are listed in the Servers.txt file.

If a computer does not have the update, the Add-Content cmdlet writes the computer name in the Missing-KB953631.txt file.

Example 4

C:\PS>(get-hotfix | sort installedon)[-1]

This command gets the most recent hotfix on the computer.

It gets the hotfixes, sorts them by the value of the InstalledOn property, and then it uses array notation to select the last item in the array.

See Also

  • Get-ComputerRestorePoint


Get-Item

Gets the item at the specified location.

Syntax

Get-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-UseTransaction] [<CommonParameters>]

Get-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-UseTransaction] [<CommonParameters>]

Description

The Get-Item cmdlet gets the item at the specified location. It does not get the contents of the item at the location unless you use a wildcard character (*) to request all the contents of the item.

The Get-Item cmdlet is used by Windows PowerShell providers to enable you to navigate through different types of data stores.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user-name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

The Exclude parameter is effective only when the command includes the contents of an item, such as C:\Windows\*, where the wildcard character specifies the contents of the C:\Windows directory.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to get items that cannot otherwise be accessed, such as hidden items. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Retrieves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

The Include parameter is effective only when the command includes the contents of an item, such as C:\Windows\*, where the wildcard character specifies the contents of the C:\Windows directory.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the item. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to an item. Get-Item gets the item at the specified location. Wildcards are permitted. This parameter is required, but the parameter name ("Path") is optional.

Use a dot (.) to specify the current location. Use the wildcard character (*) to specify all the items in the current location.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Get-Item.
Outputs | Object Get-Item returns the objects that it gets. The type is determined by the type of objects in the path.

Notes

You can also refer to Get-Item by its built-in alias, "gi". For more information, see about_Aliases.

Get-Item does not have a Recurse parameter, because it gets only an item, not its contents. To get the contents of an item recursively, use Get-ChildItem.

To navigate through the registry, use Get-Item to get registry keys and Get-ItemProperty to get registry values and data. The registry values are considered to be properties of the registry key.

The Get-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>get-item .

Directory: C:\

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         7/26/2006  10:01 AM            ps-test

Description
-----------
This command gets the current directory. The dot (.) represents the item at the current location (not its contents).

Example 2

C:\PS>get-item *

Directory: C:\ps-test

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         7/26/2006   9:29 AM            Logs
d----         7/26/2006   9:26 AM            Recs
-a---         7/26/2006   9:28 AM         80 date.csv
-a---         7/26/2006  10:01 AM         30 filenoext
-a---         7/26/2006   9:30 AM      11472 process.doc
-a---         7/14/2006  10:47 AM         30 test.txt

Description
-----------
This command gets all the items in the current directory. The wildcard character (*) represents all the contents of the current item.

Example 3

C:\PS>get-item C:\

This command gets the current directory of the C: drive. The object that is retrieved represents only the directory, not its contents.

Example 4

C:\PS>get-item C:\*

This command gets the items in the C: drive. The wildcard character (*) represents all the items in the container, not just the container.

In Windows PowerShell, use a single asterisk (*) to get contents, instead of the traditional "*.*". The format is interpreted literally, so "*.*" would not retrieve directories or file names without a dot.

Example 5

C:\PS>(get-item C:\Windows).LastAccessTime

This command gets the LastAccessTime property of the C:\Windows directory. LastAccessTime is just one property of file system directories. To see all of the properties of a directory, type "(Get-Item <directory-name>) | Get-Member".

Example 6

C:\PS>get-item hklm:\software\microsoft\powershell\1\shellids\microsoft.powershell\*

This command shows the contents of the Microsoft.PowerShell registry key. You can use Get-Item with the Windows PowerShell Registry provider to get registry keys and subkeys, but you must use Get-ItemProperty to get the registry values and data.

Example 7

C:\PS>get-item c:\Windows\* -include *.* -exclude w*

This command gets items in the Windows directory with names that include a dot (.), but do not begin with w*. This command works only when the path includes a wildcard character (*) to specify the contents of the item.

See Also

  • about_Providers
  • Clear-Item
  • Copy-Item
  • Invoke-Item
  • Move-Item
  • Set-Item
  • New-Item
  • Remove-Item
  • Rename-Item


Get-ItemProperty

Gets the properties of a specified item.

Syntax

Get-ItemProperty [-LiteralPath] <string[]> [[-Name] <string[]>] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-UseTransaction] [<CommonParameters>]

Get-ItemProperty [-Path] <string[]> [[-Name] <string[]>] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-UseTransaction] [<CommonParameters>]

Description

The Get-ItemProperty cmdlet gets the properties of the specified items. For example, you can use Get-ItemProperty to get the value of the LastAccessTime property of a file object. You can also use Get-ItemProperty to view registry entries and their values.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Includes the specified items.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the name of the property or properties to retrieve.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the item or items.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Get-ItemProperty.
Outputs | Object Get-ItemProperty returns an object for each item property that it gets. The object type depends on the object that is retrieved.

Notes

The Get-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>get-itemproperty C:\Windows

This command gets information about the C:\Windows directory.

Example 2

C:\PS>get-itemproperty C:\Test\Weather.xls | format-list

This command gets the properties of the C:\Test\Weather.xls file. The result is piped to the Format-List cmdlet to display the output as a list.

Example 3

C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion

This command displays the value name and data of each of the registry entries contained in the CurrentVersion registry subkey. Note that the command requires that there is a Windows PowerShell drive named HKLM: that is mapped to the HKEY_LOCAL_MACHINE hive of the registry. A drive with that name and mapping is available in Windows PowerShell by default. Alternatively, the path to this registry subkey can be specified by using the following alternative path that begins with the provider name followed by two colons:
Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion.

Example 4

C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion `
-name "ProgramFilesDir"

This command gets the value name and data of the ProgramFilesDir registry entry in the CurrentVersion registry subkey. The command uses the Path parameter to specify the subkey and the Name parameter to specify the value name of the entry.

Example 5

C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine

ApplicationBase         : C:\Windows\system32\WindowsPowerShell\v1.0\
ConsoleHostAssemblyName : Microsoft.PowerShell.ConsoleHost, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad
                          364e35, ProcessorArchitecture=msil
PowerShellVersion       : 2.0
RuntimeVersion          : v2.0.50727
CTPVersion              : 5
PSCompatibleVersion     : 1.0,2.0

Description
-----------
This command gets the value names and data of the registry entries in the  PowerShellEngine registry key. The results are shown in the following sample output.

Example 6

C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell

Path                                                        ExecutionPolicy
----                                                        ---------------
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe   RemoteSigned

C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell | format-list -property *

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
Path            : C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
ExecutionPolicy : RemoteSigned

Description
-----------
This example shows how to format the output of a Get-ItemProperty command in a list to make it easy to see the registry values and data and to make it easy to interpret the results.

The first command uses the Get-ItemProperty cmdlet to get the registry entries in the Microsoft.PowerShell subkey. This subkey stores options for the default shell for Windows PowerShell. The results are shown in the following sample output.

The output shows that there are two registry entries, Path and ExecutionPolicy. When a registry key contains fewer than five entries, by default it is displayed in a table, but it is often easier to view in a list.

The second command uses the same Get-ItemProperty command. However, this time, the command uses a pipeline operator (|) to send the results of the command to the Format-List cmdlet. The Format-List command uses the Property parameter with a value of * (all) to display all of the properties of the objects in a list.  The results are shown in the following sample output.

The resulting display shows the Path and ExecutionPolicy registry entries, along with several less familiar properties of the registry key object. The other properties, prefixed with "PS", are properties of Windows PowerShell custom objects, such as the objects that represent the registry keys.

See Also

  • about_Providers
  • Set-ItemProperty
  • Clear-ItemProperty
  • Copy-ItemProperty
  • Move-ItemProperty
  • New-ItemProperty
  • Remove-ItemProperty
  • Rename-ItemProperty


Get-Job

Gets Windows PowerShell background jobs that are running in the current session.

Syntax

Get-Job [-Command <string[]>] [<CommonParameters>]

Get-Job [[-InstanceId] <Guid[]>] [<CommonParameters>]

Get-Job [[-Name] <string[]>] [<CommonParameters>]

Get-Job [[-Id] <Int32[]>] [<CommonParameters>]

Get-Job [-State {<NotStarted> | <Running> | <Completed> | <Failed> | <Stopped> | <Blocked>}] [<CommonParameters>]

Description

The Get-Job cmdlet gets objects that represent the background jobs that were started in the current session. You can use Get-Job to get jobs that were started by using Start-Job, or by using the AsJob parameter of any cmdlet.

Without parameters, a "Get-Job" command gets all jobs in the current session. You can use the parameters of Get-Job to get particular jobs.

The job object that Get-Job returns contains useful information about the job, but it does not contain the job results. To get the results, use the Receive-Job cmdlet.

A Windows PowerShell background job is a command that runs "in the background" without interacting with the current session. Typically, you use a background job to run a complex command that takes a long time to complete. For more information about background jobs in Windows PowerShell, see about_Jobs.

Parameters

-Command <string[]>

Gets the jobs that include the specified command. The default is all jobs. Enter a command (as a string). You can use wildcards to specify a command pattern.

Required? | false
Position? | named
Default Value | All jobs
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Id <Int32[]>

Gets only jobs with the specified IDs.

The ID is an integer that uniquely identifies the job within the current session. It is easier to remember and to type than the instance ID, but it is unique only within the current session. You can type one or more IDs (separated by commas). To find the ID of a job, type "Get-Job" without parameters.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InstanceId <Guid[]>

Gets jobs with the specified instance IDs. The default is all jobs.

An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use Get-Job.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Name <string[]>

Gets the job with the specified friendly names. Enter a job name, or use wildcard characters to enter a job name pattern. By default, Get-Job gets all jobs in the current session.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-State <JobState>

Gets only jobs in the specified state. Valid values are NotStarted, Running, Completed, Stopped, Failed, and Blocked. By default, Get-Job gets all the jobs in the current session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.RemotingJob Get-Job returns objects that represent the jobs in the session.

Example 1

C:\PS>get-job

This command gets all background jobs started in the current session. It does not include jobs created in other sessions, even if the jobs run on the local computer.

Example 2

C:\PS>$j = get-job -name Job1

C:\PS> $ID = $j.InstanceID

C:\PS> $ID

Guid
----
03c3232e-1d23-453b-a6f4-ed73c9e29d55

C:\PS> stop-job -instanceid $ID

Description
-----------
These commands show how to get the instance ID of a job and then use it to stop a job. Unlike the name of a job, which is not unique, the instance ID is unique.

The first command uses the Get-Job cmdlet to get a job. It uses the Name parameter to identify the job. The command stores the job object that Get-Job returns in the $j variable. In this example, there is only one job with the specified name.

The second command gets the InstanceId property of the object in the $j variable and stores it in the $ID variable.

The third command displays the value of the $ID variable.

The fourth command uses Stop-Job cmdlet to stop the job. It uses the InstanceId parameter to identify the job and $ID variable to represent the instance ID of the job.

Example 3

C:\PS>get-job -command "*get-process*"

This command gets the jobs on the system that include a Get-Process command. The command uses the Command parameter of Get-Job to limit the jobs retrieved. The command uses wildcard characters (*) to get jobs that include a Get-Process command anywhere within the command string.

Example 4

C:\PS>"*get-process*" | get-job

Like the command in the  previous example, this command gets the jobs on the system that include a Get-Process command. The command uses a pipeline operator (|) to send a string (in double quotation marks) to the Get-Job cmdlet. It is the equivalent of the previous command.

Example 5

C:\PS>get-job -state NotStarted

This command gets only those jobs that have been created but have not yet been started. This includes jobs that are scheduled to run in the future and those not yet scheduled.

Example 6

C:\PS>get-job -name job*

This command gets all jobs that have job names beginning with "job". Because "job<number>" is the default name for a job, this command gets all jobs that do not have an explicitly assigned name.

Example 7

C:\PS>start-job -scriptblock {get-process} -name MyJob

C:\PS> $j = get-job -name MyJob

C:\PS> $j

Id       Name      State      HasMoreData     Location    Command
--       ----      -----      -----------     --------    -------
1        myjob     Completed  True            localhost   get-process

C:\PS> receive-job -job $j

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    124       4    13572      12080    59            1140 audiodg
    783      16    11428      13636   100             548 CcmExec
     96       4     4252       3764    59            3856 ccmsetup
...

Description
-----------
This example shows how to use Get-Job to get a job object, and then it shows how to use the job object to represent the job in a command.

The first command uses the Start-Job cmdlet to start a background job that runs a Get-Process command on the local computer. The command uses the Name parameter of Start-Job to assign a friendly name to the job.

The second command uses Get-Job to get the job. It uses the Name parameter of Get-Job to identify the job. The command saves the resulting job object in the $j variable.

The third command displays the value of the job object in the $j variable. The value of the State property shows that the job is complete. The value of the HasMoreData property shows that there are results available from the job that have not yet been retrieved.

The fourth command uses the Receive-Job cmdlet to get the results of the job. It uses the job object in the $j variable to represent the job. You can also use a pipeline operator to send a job object to Receive-Job.

Example 8

C:\PS>start-job -scriptblock {get-eventlog system}

C:\PS> invoke-command -computername S1 -scriptblock {get-eventlog system} -AsJob

C:\PS> invoke-command -computername S2 -scriptblock {start-job -scriptblock {get-eventlog system}}

C:\PS> get-job

Id    Name     State      HasMoreData   Location   Command
--    ----     -----      -----------   --------   -------
1     Job1     Running    True          localhost  get-eventlog system
2     Job2     Running    True          S1         get-eventlog system

C:\PS> invoke-command -computername S2 -scriptblock {get-job}

Id    Name     State      HasMoreData   Location   Command
--    ----     -----      -----------   --------   -------
4     Job4     Running    True          localhost  get-eventlog system

Description
-----------
This example demonstrates that the Get-Job cmdlet can get all of the jobs that were started in the current session, even if they were started by using different methods.

The first command uses the Start-Job cmdlet to start a job on the local computer.

The second command uses the AsJob parameter of Invoke-Command to start a job on the S1 computer. Even though the commands in the job run on the remote computer, the job object is created on the local computer, so you use local commands to manage the job.

The third command uses the Invoke-Command cmdlet to run a Start-Job command on the S2 computer. With this method, the job object is created on the remote computer, so you use remote commands to manage the job.

The fourth command uses Get-Job to get the jobs stored on the local computer.

The fifth command uses Invoke-Command to run a Get-Job command on the S2 computer.

The sample output shows the results of the Get-Job commands.

For more information about running background jobs on remote computers, see about_Remote_Jobs.

Example 9

C:\PS>start-job -scriptblock {get-process}

Id       Name            State      HasMoreData     Location             Command
--       ----            -----      -----------     --------             -------
1        Job1            Failed     False           localhost            get-process

C:\PS> (get-job).jobstateinfo | format-list -property *

State  : Failed
Reason :

C:\PS> get-job | format-list *

HasMoreData   : False
StatusMessage :
Location      : localhost
Command       : get-process
JobStateInfo  : Failed
Finished      : System.Threading.ManualResetEvent
InstanceId    : fb792295-1318-4f5d-8ac8-8a89c5261507
Id            : 1
Name          : Job1
ChildJobs     : {Job2}
Output        : {}
Error         : {}
Progress      : {}
Verbose       : {}
Debug         : {}
Warning       : {}
StateChanged  :

C:\PS> (get-job -name job2).jobstateinfo.reason
Connecting to remote server using WSManCreateShellEx api failed. The async callback gave the following error message :
Access is denied.

Description
-----------
This command shows how to use the job object that Get-Job returns to investigate why a job failed. It also shows how to get the child jobs of each job.

The first command uses the Start-Job cmdlet to start a job on the local computer. The job object that Start-Job returns shows that the job failed. The value of the State property is "Failed".

The second command uses Get-Job to get the job object. The command uses the dot method to get the value of the JobStateInfo property of the object. It uses a pipeline operator to send the object in the JobStateInfo property to the Format-List cmdlet, which formats all of the properties of the object (*) in a list.

The result of the Format-List command shows that the value of the Reason property of the job is blank.

The third command investigates further. It uses a Get-Job command to get the job and then uses a pipeline operator to send the entire job object to the Format-List cmdlet, which displays all of the properties of the job in a list.

The display of all properties in the job object shows that the job contains a child job named "Job2".

The fourth command uses Get-Job to get the job object that represents the Job2 child job. This is the job in which the command actually ran. It uses the dot method to get the Reason property of the JobStateInfo property.

The result shows that the job failed because of an "access denied" error. In this case, the user forgot to use the "Run as administrator" option when opening Windows PowerShell.

Because background jobs use the remoting features of Windows PowerShell, the computer must be configured for remoting to run a job, even when the job runs on the local computer.

For information about requirements for remoting in Windows PowerShell, see about_Remote_Requirements. For troubleshooting tips, see about_Remote_Troubleshooting.

See Also

  • about_Jobs
  • about_Job_Details
  • about_Remote_Jobs
  • Start-Job
  • Receive-Job
  • Wait-Job
  • Stop-Job
  • Remove-Job
  • Invoke-Command


Get-Location

Gets information about the current working location.

Syntax

Get-Location [-PSDrive <string[]>] [-PSProvider <string[]>] [-UseTransaction] [<CommonParameters>]

Get-Location [-Stack] [-StackName <string[]>] [-UseTransaction] [<CommonParameters>]

Description

The Get-Location cmdlet gets an object that represents the current directory, much like the pwd (print working directory) command.

When you move between Windows PowerShell drives, Windows PowerShell retains your location in each drive. You can use Get-Location to find your location in each drive.

You can also use Get-Location to get the current directory at run time and use it in functions and scripts, such as in a function that displays the current directory in the Windows PowerShell prompt.

If you use the Push-Location cmdlet to add locations to a path stack, you can use the Stack parameter of Get-Location to display the current stack.

Parameters

-PSDrive <string[]>

Gets the current location in the specified Windows PowerShell drive.

For example, if you are in the Certificate: drive, you can use this parameter to find your current location in the C: drive.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PSProvider <string[]>

Gets the current location in the drive supported by the specified Windows PowerShell provider.

If the specified provider supports more than one drive, Get-Location returns the location on the most recently accessed drive.

For example, if you are in the C: drive, you can use this parameter to find your current location in the drives of the Windows PowerShell Registry Provider.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Stack

Displays the locations in the default path stack.

To add paths to the default stack, use the Push-Location cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-StackName <string[]>

Displays the locations in the specified path stacks.

To create path stacks, use the Push-Location cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | PathInfo objects or StackInfo objects If you use the Stack or StackName parameters, Get-Location returns a StackInfo object. Otherwise, it returns a PathInfo object.

Notes

Locations can be stored on a stack. The Push-Location cmdlet adds a location to the top of the stack. The Pop-Location cmdlet gets the location at the top of the stack.

The ways that the PSProvider, PSDrive, Stack, and StackName parameters interact depends on the provider. Some combinations will result in errors, such as specifying both a drive and a provider that does not expose that drive. If no parameters are specified, Get-Location returns the PathInfo object for the provider that contains the current working location.

The Get-Location cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>get-location

Path
----
C:\WINDOWS

Description
-----------
This command displays your location in the current Windows PowerShell drive.

For example, if you are in the Windows directory of the C: drive, it displays the path to that directory.

Example 2

C:\PS>set-location

These commands demonstrate the use of Get-Location to display your current location in different Windows PowerShell drives.

The first command uses the Set-Location cmdlet to set the current location to the Windows subdirectory of the C: drive.

    C:\PS> set-location C:\Windows

The second command uses the Set-Location cmdlet to change the location to the HKLM:\Software\Microsoft registry key. When you change to a location in the HKLM: drive, Windows PowerShell retains your location in the C: drive.

    PS C:\WINDOWS> set-location HKLM:\Software\Microsoft
    PS HKLM:\Software\Microsoft>

The third command uses the Set-Location cmdlet to change the location to the "HKCU:\Control Panel\Input Method" registry key.

    PS HKLM:\Software\Microsoft> set-location 'HKCU:\Control Panel\Input Method'
    PS HKCU:\Control Panel\Input Method>

The fourth command uses the Get-Location cmdlet to find the current location on the C: drive. It uses the PSDrive parameter to specify the drive.

    PS HKCU:\Control Panel\Input Method> get-location -psdrive c
    Path
    ----
    C:\WINDOWS

The fifth command uses the Set-Location cmdlet to return to the C: drive. Even though the command does not specify a subdirectory, Windows PowerShell returns you to the saved location.

    PS HKCU:\Control Panel\Input Method> set-location C:
    PS C:\WINDOWS>

The sixth command uses the Get-Location cmdlet to find the current location in the drives supported by the Windows PowerShell registry provider. Get-Location returns the location of the most recently accessed registry drive, HKCU:.

    PS C:\WINDOWS> get-location -psprovider registry
    Path
    ----
    HKCU:\Control Panel\Input Method

To see the current location in the HKLM: drive, you need to use the PSDrive parameter to specify the drive. The seventh command does just this:

    PS C:\WINDOWS> get-location -psdrive HKLM
    Path
    ----
    HKLM:\Software\Microsoft

Example 3

C:\PS>set-location

These commands show how to use the Stack and StackName parameters of Get-Location to list the paths in the default and alternate path stacks.

The first command sets the current location to the Windows directory on the C: drive.

    C:\PS> set-location C:\Windows

The second command uses the Push-Location cmdlet to push the current location (C:\Windows) onto the path stack and change to the System32 subdirectory. Because no stack is specified, the current location is pushed onto the default stack.
    C:\WINDOWS>push-location System32

The third command pushes the current location (C:\Windows\System32) onto the Stack2 stack and changes the location to the WindowsPowerShell subirectory.

    C:\Windows\System32>push-location WindowsPowerShell -stack Stack2

The fourth command uses the Get-Location cmdlet to get the paths on the default path stack.

    C:\WINDOWS\system32\WindowsPowerShell>get-location -stack

    Path
    ----
    C:\WINDOWS

The last command uses the StackName parameter of Get-Location to get the paths on the Stack2 stack.

    C:\WINDOWS\system32\WindowsPowerShell>get-location -stackname Stack2

    Path
    ----
    C:\WINDOWS\system32

Example 4

C:\PS>function prompt { 'PowerShell: ' + (get-location) + '> '}

PowerShell: C:\WINDOWS>

Description
-----------
This example shows how to customize the Windows PowerShell prompt. The function that defines the prompt includes a Get-Location command, which is run whenever the prompt appears in the console.

The format of the default Windows PowerShell prompt is defined by a special function called "prompt". You can change the prompt in your console by creating a new function called "prompt".

To see the current prompt function, type the following command:

    get-content function:prompt

The command begins with the "function" keyword followed by the function name, "prompt". The function body appears within braces ( {} ).

This command defines a new prompt that begins with the string "PowerShell: ". To append the current location, it uses a Get-Location command, which runs when the prompt function is called. The prompt ends with the string "> ".

See Also

  • about_Providers
  • Pop-Location
  • Push-Location
  • Set-Location


Get-Member

Gets the properties and methods of objects.

Syntax

Get-Member [[-Name] <string[]>] [-Force] [-InputObject <psobject>] [-MemberType {<AliasProperty> | <CodeProperty> | <Property> | <NoteProperty> | <ScriptProperty> | <Properties> | <PropertySet> | <Method> | <CodeMethod> | <ScriptMethod> | <Methods> | <ParameterizedProperty> | <MemberSet> | <Event> | <All>}] [-Static] [-View {<Extended> | <Adapted> | <Base> | <All>}] [<CommonParameters>]

Description

The Get-Member cmdlet gets the "members" (properties and methods) of objects.

To specify the object, use the InputObject parameter or pipe an object to Get-Member. To retrieve information about static members (members of the class, not of the instance), use the Static parameter. To get only certain types of members, such as NoteProperties, use the MemberType parameter.

Parameters

-Force

Adds the intrinsic members (PSBase, PSAdapted, PSObject, PSTypeNames) and the compiler-generated get_ and set_ methods to the display. By default, Get-Member gets these properties in all views other than "Base" and "Adapted," but it does not display them.

The following list describes the properties that are added when you use the Force parameter:

-- PSBase: The original properties of the .NET Framework object without extension or adaptation. These are the properties defined for the object class and listed in MSDN.

-- PSAdapted: The properties and methods defined in the Windows PowerShell extended type system.

-- PSExtended: The properties and methods that were added in the Types.ps1xml files or by using the Add-Member cmdlet.

-- PSObject: The adapter that converts the base object to a Windows PowerShell PSObject object.

-- PSTypeNames: A list of object types that describe the object, in order of specificity. When formatting the object, Windows PowerShell searches for the types in the Format.ps1xml files in the Windows PowerShell installation directory ($pshome). It uses the formatting definition for the first type that it finds.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the object whose members are retrieved.

Using the InputObject parameter is not the same as piping an object to Get-Member. The differences are as follows:

-- When you pipe a collection of objects to Get-Member, Get-Member gets the members of the individual objects in the collection, such as the properties of the integers in an array of integers.

-- When you use InputObject to submit a collection of objects, Get-Member gets the members of the collection, such as the properties of the array in an array of integers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-MemberType <PSMemberTypes>

Gets only members with the specified member type. The default is All.

The valid values for this parameter are:

-- AliasProperty: A property that defines a new name for an existing property.

-- CodeMethod: A method that references a static method of a .NET Framework class.

-- CodeProperty: A property that references a static property of a .NET Framework class.

-- Event: Indicates that the object sends a message to indicate an action or a change in state.

-- MemberSet: A predefined collection of properties and methods, such as PSBase, PSObject, and PSTypeNames.

-- Method: A method of the underlying .NET Framework object.

-- NoteProperty: A property with a static value.

-- ParameterizedProperty: A property that takes parameters and parameter values.

-- Property: A property of the underlying .NET Framework object.

-- PropertySet: A predefined collection of object properties.

-- ScriptMethod: A method whose value is the output of a script.

-- ScriptProperty: A property whose value is the output of a script.

-- All: Gets all member types.

-- Methods: Gets all types of methods of the object (for example, Method, CodeMethod, ScriptMethod).

-- Properties: Gets all types of properties of the object (for example, Property, CodeProperty, AliasProperty, ScriptProperty).

Not all objects have every type of member. If you specify a member type that the object does not have, Windows PowerShell returns a null value.

To get related types of members, such as all extended members, use the View parameter. If you use the MemberType parameter with the Static or View parameters, Get-Member gets the members that belong to both sets.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of one or more properties or methods of the object. Get-Member gets only the specified properties and methods.

If you use the Name parameter with the MemberType, View, or Static parameters, Get-Member gets only the members that satisfy the criteria of all parameters.

To get a static member by name, use the Static parameter with the Name parameter.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Static

Gets only the static properties and methods of the object.

Static properties and methods are defined on the class of objects, not on any particular instance of the class.

If you use the Static parameter with the View parameter, the View parameter is ignored. If you use the Static parameter with the MemberType parameter, Get-Member gets only the members that belong to both sets.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-View <PSMemberViewTypes>

Gets only particular types of members (properties and methods). Specify one or more of the values. The default is "Adapted, Extended".

Valid values are:

-- Base: Gets only the original properties and methods of the .NET Framework object (without extension or adaptation).

-- Adapted: Gets only the properties and methods defined in the Windows PowerShell extended type system.

-- Extended: Gets only the properties and methods that were added in the Types.ps1xml files or by using the Add-Member cmdlet.

-- All: Gets the members in the Base, Adapted, and Extended views.

The View parameter determines the members retrieved, not just the display of those members.

To get particular member types, such as script properties, use the MemberType parameter. If you use the MemberType and View parameters in the same command, Get-Member gets the members that belong to both sets. If you use the Static and View parameters in the same command, the View parameter is ignored.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Get-Member
Outputs | Microsoft.PowerShell.Commands.MemberDefinition Get-Member returns an object for each property or method that its gets.

Notes

You can retrieve information about a collection object either by using the InputObject parameter or by piping the object, preceded by a comma, to Get-Member.

Example 1

C:\PS>get-service | get-member

TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
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)
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()
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;}

Description
-----------
This command displays the properties and methods of the process objects (System.ServiceProcess.ServiceController) that are generated by the Get-Service cmdlet.

The command uses the pipeline operator (|) to send the output of a Get-Service command to Get-Member.

Because the Get-Member part of the command does not have any parameters, it uses all of the default values. As such, it gets all member types, but it does not get static members and does not display intrinsic members.

Example 2

C:\PS>get-service | get-member -force

C:\PS> (get-service -schedule).psbase

This example gets all of the members (properties and methods) of the service objects (System.ServiceProcess.ServiceController) retrieved by the Get-Service cmdlet, including the intrinsic members, such as PSBase and PSObject, and the get_ and set_ methods.

The first command uses the Get-Service cmdlet to get objects that represent the services on the system. It uses a pipeline operator (|) to pass the service objects to the Get-Member cmdlet.

The Get-Member command uses the Force parameter to add the intrinsic members and compiler-generated members of the objects to the display. Get-Member gets these members, but it hides them by default.

You can use these properties and methods in the same way that you would use an adapted method of the object. The second command shows how to display the value of the PSBase property of the Schedule service.

Example 3

C:\PS>get-service	| get-member -view extended

TypeName: System.ServiceProcess.ServiceController

Name MemberType    Definition
---- ----------    ----------
Name AliasProperty Name = ServiceName

Description
-----------
This command gets the methods and properties of service objects that were extended by using the Types.ps1xml file or the Add-Member cmdlet.

The Get-Member command uses the View parameter to get only the extended members of the service objects. In this case, the extended member is the Name property, which is an alias property of the ServiceName property.

Example 4

C:\PS>get-eventlog -log system | gm -membertype scriptproperty

TypeName: System.Diagnostics.EventLogEntry

Name    MemberType     Definition
----    ----------     ----------
EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}

Description
-----------
This command gets the script properties of event log objects in the System log in Event Viewer. In this case, the only script property is the EventID.

Example 5

C:\PS>get-eventlog -log system | get-member -membertype scriptproperty

TypeName: System.Diagnostics.EventLogEntry

Name    MemberType     Definition
----    ----------     ----------
EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}

Description
-----------
This command gets the script properties of event log objects in the System log in Event Viewer.

The command uses the MemberType parameter to get only objects with a value of AliasProperty for their MemberType property.

The command returns the EventID property of the EventLog object.

Example 6

C:\PS>$a = "get-process", "get-service", "get-culture", "get-psdrive", "get-executionpolicy"

C:\PS> foreach ($cmdlet in $a) {invoke-expression $cmdlet | get-member -name machinename}

TypeName: System.Diagnostics.Process

Name        MemberType Definition
----        ---------- ----------
MachineName Property   System.String MachineName {get;}

   TypeName: System.ServiceProcess.ServiceController

Name        MemberType Definition
----        ---------- ----------
MachineName Property   System.String MachineName {get;set;}

Description
-----------
This command gets objects that have a MachineName property from a list of cmdlets.

The first command stores the names of several cmdlets in the $a variable.

The second command uses a ForEach statement to invoke each command, send the results to Get-Member, and limit the results from Get-Member to members that have the name "MachineName."

The results show that only process objects (System.Diagnostics.Process) and service objects (System.ServiceProcess.ServiceController) have a MachineName property.

Example 7

C:\PS>$a = get-member -inputobject @(1)

C:\PS>$a.count

1

C:\PS> $a = get-member -inputobject 1,2,3

   TypeName: System.Object[]
Name               MemberType    Definition
----               ----------    ----------
Count              AliasProperty Count = Length
Address            Method        System.Object& Address(Int32 )
Clone              Method        System.Object Clone()
...

C:\PS>$a.count
1

Description
-----------
This example demonstrates how to find the properties and methods of an array of objects when you have only one object of the given type.

Because the goal of the command is to find the properties of an array, the first command uses the InputObject parameter. It uses the "at" symbol (@) to indicate an array. In this case, the array contains only one object, the integer 1.

The third command uses the Get-Member cmdlet to get the properties and methods of an array of integers, and the command saves them in the $a variable.

The fourth command uses the Count property of the array to find the number of objects in the $a variable.

See Also

  • Add-Member
  • Get-Help
  • Get-Command
  • Get-PSDrive


Get-Module

Gets the modules that have been imported or that can be imported into the current session.

Syntax

Get-Module [-All] [-ListAvailable] [-Name <string[]>] [<CommonParameters>]

Get-Module [[-Name] <string[]>] [<CommonParameters>]

Description

The Get-Module cmdlet gets the modules that have been imported, or that can be imported, into the session.

Get-Module only gets modules; it does not import them. To import the modules into your session, use Import-Module.

Parameters

-All

Gets module objects for all module files.

Without the All parameter, Get-Module gets only the module object for the default module file. The cmdlet selects file types in the following order: manifest (.psd1) files, script module (.psm1) files, and binary module (.dll) files.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ListAvailable

Gets all of the modules that can be imported into the session. Get-Module gets the modules in the paths specified by the $env:PSModulePath environment variable.

Without this parameter, Get-Module gets only the modules that have been imported into the session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Gets only modules with the specified names or name patterns. Wildcards are permitted. You can also pipe the names to Get-Module.

Required? | false
Position? | 1
Default Value | All imported or available modules.
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | true

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe module names to Get-Module.
Outputs | System.Management.Automation.PSModuleInfo Get-Module returns objects that represent the modules.

Notes

You can also refer to Get-Module by its alias, "gmo". For more information, see about_Aliases.

The All parameter returns module objects for all files with a .dll file name extension, even if they do not implement cmdlets or providers.

Example 1

C:\PS>get-module

This command gets the modules that have been imported into the current session.

Example 2

C:\PS>get-module -listAvailable

This command gets the modules that can be imported into the current session.

Get-Module looks for available modules in the path specified by the $env:PSModulePath environment variable. For more information about PSModulePath, see about_Modules and about_Environment_Variables.

Example 3

C:\PS>get-module -listAvailable -all

This command gets all of the exported files for all available modules.

Example 4

C:\PS>get-module | get-member -type property

TypeName: System.Management.Automation.PSModuleInfo

Name              MemberType Definition
----              ---------- ----------
AccessMode        Property   System.Management.Automation.ModuleAcc
Description       Property   System.String Description {get;set;}
ExportedAliases   Property   System.Collections.Generic.Dictionary`
ExportedCmdlets   Property   System.Collections.Generic.Dictionary`
ExportedFunctions Property   System.Collections.Generic.Dictionary`
ExportedVariables Property   System.Collections.Generic.Dictionary`
Guid              Property   System.Guid Guid {get;}
ModuleBase        Property   System.String ModuleBase {get;}
ModuleType        Property   System.Management.Automation.ModuleTyp
Name              Property   System.String Name {get;}
NestedModules     Property   System.Collections.ObjectModel.ReadOnl
OnRemove          Property   System.Management.Automation.ScriptBlo
Path              Property   System.String Path {get;}
PrivateData       Property   System.Object PrivateData {get;set;}
SessionState      Property   System.Management.Automation.SessionSt
Version           Property   System.Version Version {get;}

Description
-----------
This command get the properties of the PSModuleInfo object that Get-Module returns. There is one object for each module file.

You can use the properties to format and filter the module objects. For more information about the properties, see "PSModule Properties" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143624.

Example 5

C:\PS>get-module -listAvailable -all | format-table -property name, moduletype, path -groupby name -auto

Name: MyTestCmdlets

Name          ModuleType Path
----          ---------- ----
MyTestCmdlets     Script C:\Windows\system32\WindowsPowerShell\v1.0\Modules\TestCmdlets\TestCmdlets.dll

   Name: PSDiagnostics

Name          ModuleType Path
----          ---------- ----
PSDiagnostics   Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\PSDiagnostics\PSDiagnostics.psd1
PSDiagnostics     Script C:\Windows\system32\WindowsPowerShell\v1.0\Modules\PSDiagnostics\PSDiagnostics.psm1

   Name: FileTransfer

Name         ModuleType Path
----         ---------- ----
FileTransfer   Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\FileTransfer\FileTransfer.psd1

Description
-----------
This command gets all module files (imported and available) and groups them by module name. This lets you see the module files that each script is exporting.

Example 6

C:\PS>$m = get-module -list -name FileTransfer | where {$_.moduletype -eq "Manifest"}

C:\PS> get-content $m.path

@{
GUID="{8FA5064B-8479-4c5c-86EA-0D311FE48875}"
Author="Microsoft Corporation"
CompanyName="Microsoft Corporation"
Copyright="© Microsoft Corporation. All rights reserved."
ModuleVersion="1.0.0.0"
Description="Windows Powershell File Transfer Module"
PowerShellVersion="2.0"
CLRVersion="2.0"
NestedModules="Microsoft.BackgroundIntelligentTransfer.Management"
FormatsToProcess="FileTransfer.Format.ps1xml"
RequiredAssemblies=Join-Path $psScriptRoot "Microsoft.BackgroundIntelligentTransfer.Management.Interop.dll"
}

Description
-----------
These commands display the contents of the module manifest for the Windows PowerShell File Transfer module.

The first command gets the PSModuleInfo object that represent the module manifest for the File Transfer module. It saves the object in the $m variable.

The second command uses dot notation to get the path to the manifest file, which is stored in the Path property of the object. Then, it uses the Get-Content cmdlet to get the content of the manifest file in the specified path.

Modules are not required to have manifest files. When they do have a manifest file, a manifest is required only to include a version number. However, manifest files often provide useful information about a module, its requirements, and its contents.

Example 7

C:\PS>get-module -listAvailable  -name FileTransfer | format-list -property *

Name              : FileTransfer
Path              : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\FileTransfer\FileTransfer.psd1
Description       : Powershell File Transfer Module
Guid              : 8fa5064b-8479-4c5c-86ea-0d311fe48875
ModuleBase        : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\FileTransfer
PrivateData       :
Version           : 1.0.0.0
ModuleType        : Manifest
AccessMode        : ReadWrite
ExportedFunctions : {}
ExportedCmdlets   : {}
NestedModules     : {}
ExportedVariables : {}
ExportedAliases   : {}
SessionState      : System.Management.Automation.SessionState
OnRemove          :

Description
-----------
This command displays all of the properties of the FileTransfer module in a list.

Because the module has not yet been imported into the session, the Exported* properties and the NestedModules property are not yet populated. These properties are populated only after the elements have been exported and the nested modules have been instantiated.

Example 8

C:\PS>dir (get-module -listavailable FileTransfer).modulebase

Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules\FileTransfer

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        12/16/2008  12:36 PM            en-US
-a---        11/19/2008  11:30 PM      16184 FileTransfer.Format.ps1xml
-a---        11/20/2008  11:30 PM       1044 FileTransfer.psd1
-a---        12/16/2008  12:20 AM     108544 Microsoft.BackgroundIntelligentTransfer.Management.Interop.dll

Description
-----------
This command lists the files in the module's directory. This is another way to determine what is in a module before you import it. Some modules might have help files or ReadMe files that describe the module.

See Also

  • Import-Module
  • New-Module
  • Remove-Module
  • about_Modules


Get-PfxCertificate

Gets information about .pfx certificate files on the computer.

Syntax

Get-PfxCertificate [-FilePath] <string[]> [<CommonParameters>]

Description

The Get-PfxCertificate cmdlet gets an object representing each specified .pfx certificate file. A .pfx file includes both the certificate and a private key.

Parameters

-FilePath <string[]>

The full path to the .pfx file of the secured file. The parameter name ("FilePath") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a file path to Get-PfxCertificate.
Outputs | System.Security.Cryptography.X509Certificates Get-PfxCertificate returns an object for each certificate that it gets.

Notes

When using the Invoke-Command cmdlet to run a Get-PfxCertificate command remotely, and the .pfx certificate file is not password protected, the value of the Authentication parameter of Invoke-Command must be "CredSSP".

Example 1

C:\PS>get-pfxcertificate -filepath C:\windows\system32\Test.pfx

Password: ******
Signer Certificate:      Matt Berg (Self Certificate)
Time Certificate:
Time Stamp:
Path:                    C:\windows\system32\zap.pfx

Description
-----------
This command gets information about the Test.pfx certificate on the system.

Example 2

C:\PS>invoke-command -computername Server01 -scriptblock {get-pfxcertificate -filepath C:\Text\TestNoPassword.pfx} -authentication CredSSP

This command gets a .pfx certificate file from the Server01 remote computer. It uses the Invoke-Command to run a Get-PfxCertificate command remotely.

When the .pfx certificate file is not password-protected, the value of the Authentication parameter of Invoke-Command must be "CredSSP".

See Also

  • Get-AuthenticodeSignature
  • Set-AuthenticodeSignature
  • about_Signing


Get-Process

Gets the processes that are running on the local computer or a remote computer.

Syntax

Get-Process [[-Name] <string[]>] [-ComputerName <string[]>] [-FileVersionInfo] [-Module] [<CommonParameters>]

Get-Process -Id <Int32[]> [-ComputerName <string[]>] [-FileVersionInfo] [-Module] [<CommonParameters>]

Get-Process -InputObject <Process[]> [-ComputerName <string[]>] [-FileVersionInfo] [-Module] [<CommonParameters>]

Description

The Get-Process cmdlet gets the processes on a local or remote computer.

Without parameters, Get-Process gets all of the processes on the local computer. You can also specify a particular process by process name or process ID (PID) or pass a process object through the pipeline to Get-Process.

By default, Get-Process returns a process object that has detailed information about the process and supports methods that let you start and stop the process. You can also use the parameters of Get-Process to get file version information for the program that runs in the process and to get the modules that the process loaded.

Parameters

-ComputerName <string[]>

Gets the processes running on the specified computers. The default is the local computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more computers. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-Process even if your computer is not configured to run remote commands.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-FileVersionInfo

Gets the file version information for the program that runs in the process.

On Windows Vista and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option to use this parameter on processes that you do not own.

Using this parameter is equivalent to getting the MainModule.FileVersionInfo property of each process object. When you use this parameter, Get-Process returns a FileVersionInfo object (System.Diagnostics.FileVersionInfo), not a process object. So, you cannot pipe the output of the command to a cmdlet that expects a process object, such as Stop-Process.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Id <Int32[]>

Specifies one or more processes by process ID (PID). To specify multiple IDs, use commas to separate the IDs. To find the PID of a process, type "get-process".

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InputObject <Process[]>

Specifies one or more process objects. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Module

Gets the modules that have been loaded by the processes.

On Windows Vista and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option to use this parameter on processes that you do not own.

This parameter is equivalent to getting the Modules property of each process object. When you use this parameter, Get-Process returns a ProcessModule object (System.Diagnostics.ProcessModule), not a process object. So, you cannot pipe the output of the command to a cmdlet that expects a process object, such as Stop-Process.

When you use both the Module and FileVersionInfo parameters in the same command, Get-Process returns a FileVersionInfo object with information about the file version of all modules.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies one or more processes by process name. You can type multiple process names (separated by commas) or use wildcard characters. The parameter name ("Name") is optional.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Diagnostics.Process You can pipe a process object to Get-Process.
Outputs | System.Diagnostics.Process, System.Diagnotics.FileVersionInfo, System.Diagnostics.ProcessModule By default, Get-Process returns a System.Diagnostics.Process object. If you use the FileVersionInfo parameter, it returns a System.Diagnotics.FileVersionInfo object. If you use the Module parameter (without the FileVersionInfo parameter), it returns a System.Diagnostics.ProcessModule object.

Notes

You cannot use the Name, ID, and InputObject parameters in the same command.

You can also refer to Get-Process by its built-in aliases, "ps" and "gps". For more information, see about_Aliases.

You can also use the properties and methods of the WMI Win32_Process object in Windows PowerShell. For information, see Get-WmiObject and the Windows Management Instrumentation (WMI) SDK.

The default display of a process is a table that includes the following columns:

-- Handles: The number of handles that the process has opened.

-- NPM(K): The amount of non-paged memory that the process is using, in kilobytes.

-- PM(K): The amount of pageable memory that the process is using, in kilobytes.

-- WS(K): The size of the working set of the process, in kilobytes. The working set consists of the pages of memory that were recently referenced by the process.

-- VM(M): The amount of virtual memory that the process is using, in megabytes. Virtual memory includes storage in the paging files on disk.

-- CPU(s): The amount of processor time that the process has used on all processors, in seconds.

-- ID: The process ID (PID) of the process.

-- ProcessName: The name of the process.

For explanations of the concepts related to processes, see the Glossary in Help and Support Center and the Help for Task Manager.

You can also use the built-in alternate views of the processes available with Format-Table, such as "StartTime" and "Priority", and you can design your own views. For more information, see Format-Table.

Example 1

C:\PS>Get-Process

This command gets a list of all of the running processes running on the local computer. For a definition of each column, see the "Additional Notes" section of the Help topic for Get-Help.

Example 2

C:\PS>Get-Process winword, explorer | format-list *

This command gets all available data about the Winword and Explorer processes on the computer. It uses the Name parameter to specify the processes, but it omits the optional parameter name. The pipeline operator (|) passes the data to the Format-List cmdlet, which displays all available properties (*) of the Winword and Explorer process objects.

You can also identify the processes by their process IDs. For example, "get-process -id 664, 2060".

Example 3

C:\PS>get-process | where-object {$_.WorkingSet -gt 20000000}

This command gets all processes that have a working set greater than 20 MB. It uses the Get-Process cmdlet to get all running processes. The pipeline operator (|) passes the process objects to the Where-Object cmdlet, which selects only the object with a value greater than 20,000,000 bytes for the WorkingSet property.

WorkingSet is one of many properties of process objects. To see all of the properties, type "Get-Process | Get-Member". By default, the values of all amount properties are in bytes, even though the default display lists them in kilobytes and megabytes.

Example 4

C:\PS>$a = get-process

C:\PS> get-process -inputobject $a | format-table -view priority

These  commands list the processes on the computer in groups based on their priority class.

The first command gets all the processes on the computer and then stores them in the $a variable.

The second command uses the InputObject parameter to pass the process objects that are stored in the $a variable to the Get-Process  cmdlet. The pipeline operator passes the objects to the Format-Table cmdlet, which formats the processes by using the Priority view.

The priority view, and other views, are defined in the PS1XML format files in the Windows PowerShell home directory ($pshome).

Example 5

C:\PS>get-process powershell -computername S1, localhost | ft @{Label="NPM(K)";Expression={[int]($_.NPM/1024)}}, @{Label="PM(K)";Expression={[int]($_.PM/1024)}},@{Label="WS(K)";Expression={[int]($_.WS/1024)}},@{Label="VM(M)";Expression={[int]($_.VM/1MB)}}, @{Label="CPU(s)";Expression={if ($_.CPU -ne $()) { $_.CPU.ToString("N")}}}, Id, MachineName, ProcessName -auto

NPM(K) PM(K) WS(K) VM(M) CPU(s)   Id MachineName ProcessName
------ ----- ----- ----- ------   -- ----------- -----------
     6 23500 31340   142        1980 S1          powershell
     6 23500 31348   142        4016 S1          powershell
    27 54572 54520   576        4428 localhost   powershell

Description
-----------
This example provides a Format-Table (alias = ft) command that adds the MachineName property to the standard Get-Process output display.

Example 6

C:\PS>get-process powershell -fileversioninfo

ProductVersion   FileVersion      FileName
--------------   -----------      --------
6.1.6713.1       6.1.6713.1 (f... C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe

Description
-----------
This command uses the FileVersionInfo parameter to get the version information for the PowerShell.exe file that is the main module for the PowerShell process.

To run this command with processes that you do not own on Windows Vista and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option.

Example 7

C:\PS>get-process sql* -module

This command uses the Module parameter to get the modules that have been loaded by the process. This command gets the modules for the processes that have names that begin with "sql".

To run this command on Windows Vista (and later versions of Windows) with processes that you do not own, you must start Windows PowerShell with the "Run as administrator" option.

Example 8

C:\PS>$p = get-wmiobject win32_process -filter "name='powershell.exe'"

C:\PS> $p.getowner()

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 3
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
Domain           : DOMAIN01
ReturnValue      : 0
User             : user01

Description
-----------
This command shows how to find the owner of a process. Because the System.Diagnostics.Process object that Get-Process returns does not have a property or method that returns the process owner, the command uses
the Get-WmiObject cmdlet to get a Win32_Process object that represents the same process.

The first command uses Get-WmiObject to get the PowerShell process. It saves it in the $p variable.

The second command uses the GetOwner method to get the owner of the process in $p. The command reveals that the owner is Domain01\user01.

Example 9

C:\PS>get-process powershell

C:\PS> get-process -id $pid

C:\PS> get-process powershell

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    308      26    52308      61780   567     3.18   5632 powershell
    377      26    62676      63384   575     3.88   5888 powershell

C:\PS> get-process -id $pid

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    396      26    56488      57236   575     3.90   5888 powershell

Description
-----------
These commands show how to use the $pid automatic variable to identify the process that is hosting the current Windows PowerShell session. You can use this method to distinguish the host process from other PowerShell processes that you might want to stop or close.

The first command gets all of the PowerShell processes in the current session.

The second command gets the PowerShell process that is hosting the current session.

See Also

  • Get-Process
  • Start-Process
  • Stop-Process
  • Wait-Process
  • Debug-Process


Get-PSBreakpoint

Gets the breakpoints that are set in the current session.

Syntax

Get-PSBreakpoint [[-Script] <string[]>] [<CommonParameters>]

Get-PSBreakpoint -Command <string[]> [-Script <string[]>] [<CommonParameters>]

Get-PSBreakpoint [-Id] <Int32[]> [<CommonParameters>]

Get-PSBreakpoint [-Type] <BreakpointType[]> [-Script <string[]>] [<CommonParameters>]

Get-PSBreakpoint -Variable <string[]> [-Script <string[]>] [<CommonParameters>]

Description

The Get-PSBreakPoint cmdlet gets the breakpoints that are set in the current session. You can use the cmdlet parameters to get particular breakpoints.

A breakpoint is a point in a command or script where execution stops temporarily so that you can examine the instructions. Get-PSBreakpoint is one of several cmdlets designed for debugging Windows PowerShell scripts and commands. For more information about the Windows PowerShell debugger, see about_Debuggers.

Parameters

-Command <string[]>

Gets command breakpoints that are set on the specified command names. Enter the command names, such as the name of a cmdlet or function.

Required? | true
Position? | named
Default Value | All breakpoints
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Id <Int32[]>

Gets the breakpoints with the specified breakpoint IDs. Enter the IDs in a comma-separated list. You can also pipe breakpoint IDs to Get-PSBreakpoint.

Required? | true
Position? | 1
Default Value | All breakpoints
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Script <string[]>

Gets only the breakpoints in the specified scripts. Enter the path (optional) and names of one or more script files. The default location is the current directory.

Required? | false
Position? | named
Default Value | All breakpoints
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Type <BreakpointType[]>

Gets only breakpoints of the specified types. Enter one or more types. Valid values are Line, Command, and Variable. You can also pipe breakpoint types to Get-PSBreakpoint.

Required? | true
Position? | 1
Default Value | All breakpoints
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Variable <string[]>

Gets variable breakpoints that are set on the specified variable names. Enter the variable names without dollar signs.

Required? | true
Position? | named
Default Value | All breakpoints
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Int32, Microsoft.PowerShell.Commands.BreakpointType You can pipe breakpoint IDs and breakpoint types to Get-PSBreakpoint.
Outputs | Breakpoint object (System.Management.Automation.LineBreakpoint, System.Management.Automation.VariableBreakpoint, System.Management.Automation.CommandBreakpoint) Get-PSBreakPoint returns objects that represent the breakpoints in the session.

Notes

You can use Get-PSBreakpoint or its alias, "gbp".

Example 1

C:\PS>get-psbreakpoint

This command gets all breakpoints set on all scripts and functions in the current session.

Example 2

C:\PS>get-psbreakpoint -Id 2

Function   : Increment
Action     :
Enabled    : True
HitCount   : 0
Id         : 2
Script     : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1

Description
-----------
This command gets the breakpoint with breakpoint ID 2.

Example 3

C:\PS>$b = set-psbreakpoint -script sample.ps1 -function increment

C:\PS> $b.Id | get-psbreakpoint

These commands show how to get a breakpoint by piping a breakpoint ID to Get-PSBreakpoint.

The first command uses the Set-PSBreakpoint cmdlet to create a breakpoint on the Increment function in the Sample.ps1 script. It saves the breakpoint object in the $b variable.

The second command uses the dot operator (.) to get the Id property of the breakpoint object in the $b variable. It uses a pipeline operator (|) to send the ID to the Get-PSBreakpoint cmdlet.

As a result, Get-PSBreakpoint gets the breakpoint with the specified ID.

Example 4

C:\PS>get-psbreakpoint -script Sample.ps1, SupportScript.ps1

This command gets all of the breakpoints in the Sample.ps1 and SupportScript.ps1 files.

This command does not get other breakpointS that might be set in other scripts or on functions in the session.

Example 5

C:\PS>get-psbreakpoint -command Read-Host, Write-Host -script Sample.ps1

This command gets all Command breakpoints that are set on Read-Host or Write-Host commands in the Sample.ps1 file.

Example 6

C:\PS>get-psbreakpoint -type Command -script Sample.ps1

This command gets all Command breakpoints in the Sample.ps1 file.

Example 7

C:\PS>get-psbreakpoint -variable Index, Swap

This command gets breakpoints that are set on the $index and $swap variables in the current session.

Example 8

C:\PS>get-psbreakpoint -type line, variable -script Sample.ps1

This command gets all line and variable breakpoints in the Sample.ps1 script.

See Also

  • about_Debuggers
  • Set-PSBreakpoint
  • Disable-PSBreakpoint
  • Enable-PSBreakpoint
  • Remove-PSBreakpoint
  • Get-PSCallStack


Get-PSCallStack

Displays the current call stack.

Syntax

Get-PSCallStack [<CommonParameters>]

Description

The Get-PSCallStack cmdlet displays the current call stack.

Although it is designed to be used with the Windows PowerShell debugger, you can use this cmdlet to display the call stack in a script or function outside of the debugger.

To run a Get-PSCallStack command while in the debugger, type "k" or "get-pscallstack".

Parameters

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to this cmdlet.
Outputs | System.Management.Automation.CallStackFrame Get-PSCallStack returns an object that represents the items in the call stack.

Example 1

C:\PS>function my-alias {
   $p = $args[0]
   get-alias | where {$_.definition -like "*$p"} | ft definition, name -auto
}

PS C:\ps-test> set-psbreakpoint -command my-alias

Command    : my-alias
Action     :
Enabled    : True
HitCount   : 0
Id         : 0
Script     : prompt

PS C:\ps-test> my-alias get-content
Entering debug mode. Use h or ? for help.

Hit Command breakpoint on 'prompt:my-alias'

my-alias get-content

[DBG]: PS C:\ps-test> s
$p = $args[0]

DEBUG: Stepped to ':    $p = $args[0]    '

[DBG]: PS C:\ps-test> s
get-alias | Where {$_.Definition -like "*$p*"} | ft Definition,

[DBG]: PS C:\ps-test>get-pscallstack

Name        CommandLineParameters         UnboundArguments              Location
----        ---------------------         ----------------              --------
prompt      {}                            {}                            prompt
my-alias    {}                            {get-content}                 prompt
prompt      {}                            {}                            prompt

[DBG]: PS C:\ps-test> o

Definition  Name
----------  ----
Get-Content gc
Get-Content cat
Get-Content type

Description
-----------
This command uses the Get-PSCallStack cmdlet to display the call stack for My-Alias, a simple function that gets the aliases for a cmdlet name.

The first command enters the function at the Windows PowerShell prompt. The second command uses the Set-PSBreakpoint cmdlet to set a breakpoint on the My-Alias function. The third command uses the My-Alias function to get all of the aliases in the current session for the Get-Content cmdlet.

The debugger breaks in at the function call. Two consecutive step-into (s) commands begin executing the function line by line. Then, a Get-PSCallStack command is used to retrieve the call stack.

The final command is a Step-Out command (o) that exits the debugger and continues executing the script to completion.

See Also

  • about_Debuggers
  • Set-PSBreakpoint
  • Get-PSBreakpoint
  • Enable-PSBreakpoint
  • Disable-PSBreakpoint
  • Remove-PSBreakpoint


Get-PSDrive

Gets the Windows PowerShell drives in the current session.

Syntax

Get-PSDrive [-LiteralName] <string[]> [-PSProvider <string[]>] [-Scope <string>] [-UseTransaction] [<CommonParameters>]

Get-PSDrive [[-Name] <string[]>] [-PSProvider <string[]>] [-Scope <string>] [-UseTransaction] [<CommonParameters>]

Description

The Get-PSDrive cmdlet gets the Windows PowerShell drives in the current session. You can get a particular drive or all drives in the console.

Get-PSDrive gets the following drives:

-- Windows logical drives on the computer, including drives mapped to network shares.

-- Drives exposed by Windows PowerShell providers (such as the Certificate:, Function:, and Alias: drives) and the HKLM: and HKCU: drives that are exposed by the Windows PowerShell Registry Provider.

-- Drives that you create by using New-PSDrive.

Get-PSDrive does not get Windows mapped drives that are added or created after the Windows PowerShell console is opened.

Parameters

-LiteralName <string[]>

Specifies the name of the Windows PowerShell drive.

The value of LiteralName is used exactly as it is typed. No characters are interpreted as wildcards. If the name includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Gets only the specified drives. Type the drive name or letter without a colon (:).

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PSProvider <string[]>

Gets only the drives supported by the specified Windows PowerShell provider. Type the name of a provider, such as FileSystem, Registry, or Certificate.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Scope <string>

Gets only the Windows PowerShell drives in the specified scope. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Get-PSDrive.
Outputs | System.Management.Automation.PSDriveInfo Get-PSDrive returns objects that represent the Windows PowerShell drives in the session.

Notes

The Get-PSDrive cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>get-psdrive

Name       Provider      Root
----       --------      ----
Alias      Alias
C          FileSystem    C:\
cert       Certificate   \
D          FileSystem    D:\
Env        Environment
Function   Function
HKCU       Registry      HKEY_CURRENT_USER
HKLM       Registry      HKEY_LOCAL_MACHINE
Variable   Variable
X          FileSystem    X:\

Description
-----------
This command gets the Windows PowerShell drives in the current session.

The output shows the hard drive (C:) and CD-ROM drive (D:) on the computer, the drives exposed by the Windows PowerShell providers (Alias:, Cert:, Env:, Function:, HKCU:, HKLM:, and Variable:), and a drive mapped to a network share (X:).

Example 2

C:\PS>get-psdrive d

Name       Provider      Root
----       --------      ----
D          FileSystem    D:\

Description
-----------
This command displays the D: drive on the computer. Note that the drive letter is not followed by a colon.

Example 3

C:\PS>get-psdrive -psprovider filesystem

Name       Provider      Root
----       --------      ----
C          FileSystem    C:\
D          FileSystem    D:\
X          FileSystem    X:\
Y          FileSystem    \\Server01\Public
Z          FileSystem    C:\Windows\System32

Description
-----------
This command displays all of the drives that are supported by the Windows PowerShell FileSystem provider. This includes fixed drives, logical partitions, mapped network drives, and drives that you create by using New-PSDrive that are mapped to the file system drives.

This example shows that drives created by New-PSDrive have the name of the mapped location in the value of the Root property. Windows drives just have the root of the drive letter.

Example 4

C:\PS>if (!(get-psdrive X)) {
    new-psdrive -name X -psprovider Registry -root HKLM:\Network
}
else { write-host "The X: drive is already in use." }

This command checks to see whether the X drive is already in use as the Windows PowerShell drive name. If it is not, the command uses the New-PSDrive cmdlet to create a Windows PowerShell drive that is mapped to the HKLM:\Network registry key.

Example 5

C:\PS>get-psdrive -provider filesystem

C:\PS> get-psdrive -provider filesystem

Name       Provider      Root
----       --------      ----
C          FileSystem    C:\
D          FileSystem    D:\
X          FileSystem    X:\
Y          FileSystem    \\Server01\Public
Z          FileSystem    C:\Windows\System32

C:\PS> net use
New connections will be remembered.

Status       Local     Remote                    Network
-------------------------------------------------------------------------------
             X:        \\Server01\Public         Microsoft Windows Network

C:\PS> [System.IO.DriveInfo]::getdrives()

Name               : C:\
DriveType          : Fixed
DriveFormat        : NTFS
IsReady            : True
AvailableFreeSpace : 39831498752
TotalFreeSpace     : 39831498752
TotalSize          : 79900368896
RootDirectory      : C:\
VolumeLabel        :
Name               : D:\
DriveType          : CDRom
DriveFormat        :
IsReady            : False
AvailableFreeSpace :
TotalFreeSpace     :
TotalSize          :
RootDirectory      : D:\
VolumeLabel        :
Name               : X:\
DriveType          : Network
DriveFormat        : NTFS
IsReady            : True
AvailableFreeSpace : 36340559872
TotalFreeSpace     : 36340559872
TotalSize          : 36413280256
RootDirectory      : X:\
VolumeLabel        : D_Drive

C:\PS> get-wmiobject win32_logicaldisk

DeviceID     : C:
DriveType    : 3
ProviderName :
FreeSpace    : 39831252992
Size         : 79900368896
VolumeName   :
DeviceID     : D:
DriveType    : 5
ProviderName :
FreeSpace    :
Size         :
VolumeName   :
DeviceID     : X:
DriveType    : 4
ProviderName : \\server01\public
FreeSpace    : 36340559872
Size         : 36413280256
VolumeName   : D_Drive

C:\PS> get-wmiobject win32_networkconnection
LocalName                     RemoteName
--------------               ------------
x:                            \\server01\public

Description
-----------
This example compares the types of file system drives that are displayed by Get-PSDrive to those displayed by using other methods. This example demonstrates different ways to display drives in Windows PowerShell, and it shows that the drives created by using New-PSDrive are accessible only in Windows PowerShell.

The first command uses Get-PSDrive to get all of the file system drives in the Windows PowerShell console. This includes the fixed drives (C: and D:), the mapped network drive (X:), and two Windows PowerShell drives (Y: and Z:) that were created by using New-PsDrive.

A "net use" command, which displays Windows mapped network drives, displays only the X drive. It does not display drives that are created by New-PSDrive. It shows that the X: drive is also mapped to \\Server01\Public.

The third command uses the GetDrives method of the Microsoft .NET Framework System.IO.DriveInfo class. This command gets the Windows file system drives, including drive X:, but it does not get the drives created by New-PSDrive.

The fourth command uses the Get-WmiObject cmdlet to display the instances of the Win32_LogicalDisk class. It returns the C:, D:, and X: drives, but not the drives created by New-PSDrive.

The last command uses the Get-WmiObject cmdlet to display the instances of the Win32_NetworkConnection class. Like "net use", it returns only the X: drive.

See Also

  • about_Providers
  • New-PSDrive
  • Remove-PSDrive
  • Get-Help
  • Get-Command
  • Get-Member


Get-PSProvider

Gets information about the specified Windows PowerShell provider.

Syntax

Get-PSProvider [[-PSProvider] <string[]>] [<CommonParameters>]

Description

The Get-PSProvider cmdlet gets the Windows PowerShell providers in the current session. You can get a particular drive or all drives in the session.

Windows PowerShell providers let you access a variety of data stores as though they were file system drives. For information about Windows PowerShell providers, see about_Providers.

Parameters

-PSProvider <string[]>

Specifies the name or names of the Windows PowerShell providers about which to retrieve information.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to this cmdlet.
Outputs | System.Management.Automation.ProviderInfo Get-PSProvider returns objects that represent the Windows PowerShell providers in the session.

Example 1

C:\PS>get-psprovider

This command displays a list of all available Windows PowerShell providers.

Example 2

C:\PS>get-psprovider f*, r* | format-list

This command displays a list of all Windows PowerShell providers with names that begin with the letter "f" or "r".

Example 3

C:\PS>get-psprovider | format-table name, module, pssnapin -auto

Name        Module       PSSnapIn
----        ------       --------
Test        TestModule
WSMan                    Microsoft.WSMan.Management
Alias                    Microsoft.PowerShell.Core
Environment              Microsoft.PowerShell.Core
FileSystem               Microsoft.PowerShell.Core
Function                 Microsoft.PowerShell.Core
Registry                 Microsoft.PowerShell.Core
Variable                 Microsoft.PowerShell.Core
Certificate              Microsoft.PowerShell.Security

C:\PS> get-psprovider | where {$_.pssnapin -eq "Microsoft.PowerShell.Security"}

Name            Capabilities      Drives
----            ------------      ------
Certificate     ShouldProcess     {cert}

Description
-----------
These commands find the Windows PowerShell snap-ins or modules that added providers to your session. All Windows PowerShell elements, including providers, originate in a snap-in or in a module.

These commands use the PSSnapin and Module properties of the ProviderInfo object that Get-PSProvider returns. The values of these properties contain the name of the snap-in or module that adds the provider.

The first command gets all of the providers in the session and formats them in a table with the values of their Name, Module, and PSSnapin properties.

The second command uses the Where-Object cmdlet to get the providers that come from the Microsoft.PowerShell.Security snap-in.

See Also

  • about_Providers


Get-PSSession

Gets the Windows PowerShell sessions (PSSessions) in the current session.

Syntax

Get-PSSession [[-ComputerName] <string[]>] [<CommonParameters>]

Get-PSSession [-Id] <Int32[]> [<CommonParameters>]

Get-PSSession [-InstanceId <Guid[]>] [<CommonParameters>]

Get-PSSession [-Name <string[]>] [<CommonParameters>]

Description

The Get-PSSession cmdlet gets the Windows PowerShell sessions (PSSessions) that were created in the current session.

Without parameters, Get-PSSession gets all of the PSSessions created in the current session. You can use the parameters of Get-PSSession to get the sessions that are connected to particular computers, or you can identify sessions by their names, IDs, or instance IDs.

For more information about Windows PowerShell sessions, see about_PSSessions.

Parameters

-ComputerName <string[]>

Gets only the PSSessions that are connected to the specified computers. Wildcards are permitted.

Type the NetBIOS name, an IP address, or a fully-qualified domain name of one or more computers. To specify the local computer, type the computer name, "localhost", or a dot (.).

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Id <Int32[]>

Gets only the PSSessions with the specified IDs. Type one or more IDs (separated by commas), or use the range operator (..) to specify a range of IDs.

An ID is an integer that uniquely identifies the PSSession in the current session. It is easier to remember and type than the InstanceId, but it is unique only within the current session. To find the ID of a PSSession, use Get-PSSession without parameters.

Required? | true
Position? | 1
Default Value | All sessions in the shell
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InstanceId <Guid[]>

Gets only the PSSessions with the specified instance IDs.

The instance ID is a GUID that uniquely identifies a PSSession on a local or remote computer. The InstanceID is unique, even when you have multiple sessions running in Windows PowerShell.

The InstanceID is stored in the InstanceID property of the object that represents a PSSession. To find the InstanceID of the PSSessions in the current session, type "get-pssession | Format-Table Name, ComputerName, InstanceId".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Name <string[]>

Gets only the PSSessions with the specified friendly names. Wildcards are permitted.

To find the names of the PSSessions in the current session, type "get-pssession" without parameters.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.Runspaces.PSSession Get-PSSession returns a PSSession object for each PSSession that it gets.

Notes

Get-PSSession gets the PSSessions that were created in the current session. It does not get the session that is created when you open Windows PowerShell, and it does not get PSSessions that were created in other sessions or on other computers, even if they connect to the local computer.

Example 1

C:\PS>get-pssession

This command gets all of the PSSessions that were created in the current session.

It does not get PSSessions that were created in other sessions or on other computers, even if they connect to this computer.

Example 2

C:\PS>$s = get-pssession -computername Server02

This command gets the PSSessions that are connected to the Server02 computer and saves them in the $p variable.

Example 3

C:\PS>new-pssession -computername Server01, Server02, Server03

C:\PS> $s1, $s2, $s3 = get-pssession

This example shows how to save the results of a Get-PSSession command in multiple variables.

The first command uses the New-PSSession cmdlet to create PSSessions on three remote computers.

The second command uses a Get-PSSession cmdlet to get the three PSSessions. It then saves each of the PSSessions in a separate variable.

When Windows PowerShell assigns an array of objects to an array of variables, it assigns the first object to the first variable, the second object to the second variable, and so on. If there are more objects than variables, it assigns all remaining objects to the last variable in the array. If there are more variables than objects, the extra variables are not used.

Example 4

C:\PS>get-pssession | format-table -property computername, InstanceID

C:\PS> $s = get-pssession -InstanceID a786be29-a6bb-40da-80fb-782c67f7db0f

C:\PS> remove-pssession -session $s

This example shows how to get a PSSession by using its instance ID, and then to delete the PSSession.

The first command gets all of the PSSessions on the local computer. It sends the PSSessions to the Format-Table cmdlet, which displays the ComputerName and InstanceID properties of each PSSession.

The second command uses the Get-PSSession cmdlet to get a particular PSSession and to save it in the $s variable. The command uses the InstanceID parameter to identify the PSSession.

The third command uses the Remove-PSSession cmdlet to delete the PSSession in the $s variable.

Example 5

C:\PS>get-pssession -computername Serv*

This command gets all the PSSessions that connect to computers that have computer names that begin with "Serv".

Example 6

C:\PS>get-pssession -name Test*, Ux*

This command gets PSSessions that have names that begin with "Test" or "Ux".

Example 7

C:\PS>get-pssession 2

This command gets the PSSession with ID 2.

See Also

  • about_PSSessions
  • about_Remote
  • New-PSSession
  • Remove-PSSession
  • Enter-PSSession
  • Exit-PSSession
  • Invoke-Command


Get-PSSessionConfiguration

Gets the registered session configurations on the computer.

Syntax

Get-PSSessionConfiguration [[-Name] <string[]>] [<CommonParameters>]

Description

The Get-PSSessionConfiguration cmdlet gets the session configurations that have been registered on the local computer. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users.

To create and register a session configuration, use the Register-PSSessionConfiguration cmdlet.

Parameters

-Name <string[]>

Gets only the session configurations with the specified name or name pattern. Enter one or more session configuration names. Wildcards are permitted.

Required? | false
Position? | 1
Default Value | All session configurations on the local computer
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration

Notes

To run this cmdlet on Windows Vista, Windows Server 2008, and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option.

To view the session configurations on the computer, you must be a member of the Administrators group on the computer.

To run a Get-PSSessionConfiguration command on a remote computer, Credential Security Service Provider (CredSSP) authentication must be enabled in the client settings on the local computer (by using the Enable-WSManCredSSP cmdlet) and in the service settings on the remote computer, and you must use the CredSSP value of the Authentication parameter when establishing the remote session. Otherwise, access is denied.

Example 1

C:\PS>get-pssessionconfiguration

This command gets the session configurations on the computer.

Example 2

C:\PS>get-pssessionconfiguration -name Microsoft*

Name                      PSVersion  StartupScript        Permission
----                      ---------  -------------        ----------
microsoft.powershell      2.0                             BUILTIN\Administrators AccessAll...
microsoft.powershell32    2.0                             BUILTIN\Administrators AccessAll...

Description
-----------
This command uses the Name parameter of Get-PSSessionConfiguration to get only the session configurations with names that begin with "Microsoft".

This command gets the two default session configurations that come with Windows PowerShell.

Example 3

C:\PS>Get-PSSessionConfiguration -name microsoft.powershell | get-member

TypeName: Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration

Name                   MemberType     Definition
----                   ----------     ----------
Equals                 Method         bool Equals(System.Object obj)
GetHashCode            Method         int GetHashCode()
GetType                Method         type GetType()
ToString               Method         string ToString()
Capability             NoteProperty   System.Object[] Capability=System.Object[]
ExactMatch             NoteProperty   System.String ExactMatch=False
Filename               NoteProperty   System.String Filename=%windir%\system32\pwrshplugin.dll
lang                   NoteProperty   System.String lang=en-US
Name                   NoteProperty   System.String Name=microsoft.powershell
PSVersion              NoteProperty   System.String PSVersion=2.0
ResourceUri            NoteProperty   System.String ResourceUri=http://schemas.microsoft.com/powershell/microsoft.powershell
SDKVersion             NoteProperty   System.String SDKVersion=1
SecurityDescriptorSddl NoteProperty   System.String SecurityDescriptorSddl=O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
SupportsOptions        NoteProperty   System.String SupportsOptions=true
Uri                    NoteProperty   System.String Uri=http://schemas.microsoft.com/powershell/microsoft.powershell
xmlns                  NoteProperty   System.String xmlns=http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration
XmlRenderingType       NoteProperty   System.String XmlRenderingType=text
Permission             ScriptProperty System.Object Permission {get=trap { continue; }...

C:\PS> Get-PSSessionConfiguration -name microsoft.powershell | format-list -property *

Name                   : microsoft.powershell
Filename               : %windir%\system32\pwrshplugin.dll
SDKVersion             : 1
XmlRenderingType       : text
lang                   : en-US
PSVersion              : 2.0
ResourceUri            : http://schemas.microsoft.com/powershell/microsoft.powershell
SupportsOptions        : true
Capability             : {Shell}
Uri                    : http://schemas.microsoft.com/powershell/microsoft.powershell
SecurityDescriptorSddl : O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
ExactMatch             : False
xmlns                  : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration
Permission             : BUILTIN\Administrators AccessAllowed

Description
-----------
These commands examine the PSSessionConfiguration object that Get-PSSessionConfiguration returns.

The first command uses the Get-PSSessionConfiguration cmdlet to get the Microsoft.PowerShell default configuration.

The second command uses a pipeline operator (|) to send the object that Get-PSSessionConfiguration returns to the Get-Member cmdlet. The output shows the properties and methods of the object.

The third command sends the same object to the Format-List cmdlet. The Property parameter with a value of * (all) directs Format-List to display all of the properties and property values of the object in a list.

The output of this command has very useful information, including the location of the .dll that implements the configuration type, the resource Uniform Resource Identifier (URI) for the endpoint that is created, and the Security Descriptor Definition Language (SDDL) for the configuration.

Example 4

C:\PS>dir wsman:\localhost\plugin

WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin

Name                      Type                 Keys
----                      ----                 ----
Event Forwarding Plugin   Container            {Name=Event Forwarding Plugin}
MaintenanceShell          Container            {Name=MaintenanceShell}
microsoft.powershell      Container            {Name=microsoft.powershell}
microsoft.powershell32    Container            {Name=microsoft.powershell32}
WMI Provider              Container            {Name=WMI Provider}

Description
-----------
This command uses the Get-ChildItem cmdlet (alias = dir) in the WSMan: provider drive to look at the content of the Plugin node.

This is another way to look at the session configurations on the computer.

The PlugIn node contains ContainerElement objects (Microsoft.WSMan.Management.WSManConfigContainerElement) that represent the registered Windows PowerShell session configurations, along with other plug-ins for WS-Management.

Example 5

C:\PS>enable-wsmanCredSSP -delegate server02

C:\PS> connect-wsman server02

C:\PS> set-item wsman:\server02*\service\auth\credSSP -value $true

C:\PS> invoke-command -scriptblock {Get-PSSessionConfiguration} -computername Server02 -authentication CredSSP -credential Domain01\Admin01

Name                      PSVersion  StartupScript        Permission                          PSComputerName
----                      ---------  -------------        ----------                          --------------
microsoft.powershell      2.0                             BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com
microsoft.powershell32    2.0                             BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com
MyX86Shell                2.0        c:\test\x86Shell.ps1 BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com

Description
-----------
This example shows how to run a Get-PSSessionConfiguration command on a remote computer. The command requires that CredSSP delegation be enabled in the client settings on the local computer and in the service settings on the remote computer. To run the commands in this example, you must be a member of the Administrators group on the local computer and the remote computer.

The first command uses the Enable-WSManCredSSP cmdlet to enable CredSSP delegation from the Server01 local computer to the Server02 remote computer. This configures the CredSSP client setting on the local computer.

The second command uses the Connect-WSMan cmdlet to connect to the Server02 computer. This action adds a node for the Server02 computer to the WSMan: drive on the local computer, allowing you to view and change the WS-Management settings on the Server02 computer.

The third command uses the Set-Item cmdlet to change the value of the CredSSP item in the Service node of the Server02 computer to True. This configures the service settings on the remote computer.

The fourth command uses the Invoke-Command cmdlet to run a Get-PSSessionConfiguration command on the Server02 computer. The command uses the Credential parameter, and it uses the Authentication parameter with a value of CredSSP.

Example 6

C:\PS>(get-PSSessionConfiguration -name CustomShell).resourceURI

http://schemas.microsoft.com/powershell/microsoft.CustomShell

Description
-----------
This command uses the Get-PSSessionConfiguration cmdlet to get the resource URI of a session configuration.

This command is useful when setting the value of the $PSSessionConfigurationName preference variable, which takes a resource URI.

The $PSSessionConfiguationName variable specifies the default configuration that is used when you create a session. This variable is set on the local computer, but it specifies a configuration on the remote computer. For more information about the $PSSessionConfiguration variable, see about_Preference_Variables.

See Also

  • about_Session_Configurations
  • Disable-PSSessionConfiguration
  • Enable-PSSessionConfiguration
  • Register-PSSessionConfiguration
  • Set-PSSessionConfiguration
  • Unregister-PSSessionConfiguration
  • WS-Management Provider


Get-PSSnapin

Gets the Windows PowerShell snap-ins on the computer.

Syntax

Get-PSSnapin [[-Name] <string[]>] [-Registered] [<CommonParameters>]

Description

The Get-PSSnapin cmdlet gets the Windows PowerShell snap-ins that have been added to the current session or that have been registered on the system. The snap-ins are listed in the order in which they are detected.

Get-PSSnapin gets only registered snap-ins. To register a Windows PowerShell snap-in, use the InstallUtil tool included with the Microsoft .NET Framework 2.0. For more information, see "How to Register Cmdlets, Providers, and Host Applications" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143619.

Parameters

-Name <string[]>

Gets only the specified Windows PowerShell snap-ins. Enter the names of one or more Windows PowerShell snap-ins. Wildcards are permitted.

The parameter name ("Name") is optional.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Registered

Gets the Windows PowerShell snap-ins that have been registered on the system (even if they have not yet been added to the session).

The snap-ins that are installed with Windows PowerShell do not appear in this list.

Without this parameter, Get-PSSnapin gets the Windows PowerShell snap-ins that have been added to the session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to Get-PSSnapin.
Outputs | System.Management.Automation.PSSnapInInfo Get-PSSnapin returns an object for each snap-in that it gets.

Notes

You can refer to Get-PSSnapin by its built-in alias, "psnp". For more information, see about_Aliases.

Example 1

C:\PS>get-PSSnapIn

This command gets the Windows PowerShell snap-ins that are currently loaded in the session. This includes the snap-ins that are installed with Windows PowerShell and those that have been added to the session.

Example 2

C:\PS>get-PSSnapIn -registered

This command gets the Windows PowerShell snap-ins that have been registered on the computer, including those that have already been added to the session. The output does not include snap-ins that are installed with Windows PowerShell or Windows PowerShell snap-in dynamic-link libraries (DLLs) that have not yet been registered on the system.

Example 3

C:\PS>get-PSSnapIn smp*

This command gets the Windows PowerShell snap-ins in the current session that have names that begin with "smp".

See Also

  • Add-PSSnapin
  • Remove-PSSnapin


Get-Random

Gets a random number, or selects objects randomly from a collection.

Syntax

Get-Random [-InputObject] <Object[]> [-Count <int>] [-SetSeed <int>] [<CommonParameters>]

Get-Random [[-Maximum] <Object>] [-Minimum <Object>] [-SetSeed <int>] [<CommonParameters>]

Description

The Get-Random cmdlet gets a randomly selected number. If you submit a collection of objects to Get-Random, it gets one or more randomly selected objects from the collection.

Without parameters or input, a Get-Random command returns a randomly selected 32-bit unsigned integer between 0 (zero) and Int32.MaxValue (0x7FFFFFFF, 2,147,483,647).

You can use the parameters of Get-Random to specify a seed number, minimum and maximum values, and the number of objects returned from a submitted collection.

Parameters

-Count <int>

Determines how many objects are returned. The default is 1. If the value of Count exceeds the number of objects in the collection, Get-Random returns all of the objects in random order.

Required? | false
Position? | named
Default Value | 1
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <Object[]>

Specifies a collection of objects. Get-Random gets randomly selected objects in random order from the collection. Enter the objects, a variable that contains the objects, or a command or expression that gets the objects. You can also pipe a collection of objects to Get-Random.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Maximum <Object>

Specifies a maximum value for the random number. Get-Random returns a value that is less than the maximum (not equal). Enter a 32-bit integer or a double-precision floating-point number, or an object that can be converted to an integer or double, such as a numeric string ("100"). The value of Maximum must be greater than (not equal to) the value of Minimum.

If the value of Maximum or Minimum is a floating-point number, Get-Random returns a randomly selected floating-point number.

If the value of Minimum is a double (a floating-point number), the default value of Maximum is Double.MaxValue. Otherwise, the default value is Int32.MaxValue (2,147,483,647 or 0x7FFFFFFF).

Required? | false
Position? | 1
Default Value | Int32.MaxValue
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Minimum <Object>

Specifies a minimum value for the random number. Enter a 32-bit integer or a double-precision floating-point number, or an object that can be converted to an integer or double, such as a numeric string ("100"). The default value is 0 (zero).

The value of Minimum must be less than (not equal to) the value of Maximum. If the value of Maximum or Minimum is a floating-point number, Get-Random returns a randomly selected floating-point number.

Required? | false
Position? | named
Default Value | 0
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SetSeed <int>

Specifies a seed value for the random number generator. This seed value is used for the current command and for all subsequent Get-Random commands in the current session until you use SetSeed again or close the session. You cannot reset the seed to its default, clock-based value.

The SetSeed parameter is not required. By default, Get-Random uses the system clock to generate a seed value. Because SetSeed results in non-random behavior, it is typically used only when trying to reproduce behavior, such as when debugging or analyzing a script that includes Get-Random commands.

Required? | false
Position? | named
Default Value | System clock
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Object You can pipe one or more objects to Get-Random. Get-Random selects values randomly from the piped objects.
Outputs | System.Object Get-Random returns an integer or floating-point number, or an object selected randomly from a submitted collection.

Notes

Get-Random sets a default seed for each session based on the system time clock when the session starts.

Example 1

C:\PS>get-random

3951433

Description
-----------
This command gets a random integer between 0 (zero) and Int32.MaxValue.

Example 2

C:\PS>get-random -maximum 100

47

Description
-----------
This command gets a random integer between 0 (zero) and 99.

Example 3

C:\PS>get-random -minimum -100 -maximum 100

-56

Description
-----------
This command gets a random integer between -100 and 99.

Example 4

C:\PS>get-random -min 10.7 -max 20.93

18.08467273887

Description
-----------
This command gets a random floating-point number greater than or equal to 10.7 and less than 20.92.

Example 5

C:\PS>get-random -input 1, 2, 3, 5, 8, 13

8

Description
-----------
This command gets a randomly selected number from the specified array.

Example 6

C:\PS>get-random -input 1, 2, 3, 5, 8, 13 -count 3

3
1
13

Description
-----------
This command gets three randomly selected numbers in random order from the array.

Example 7

C:\PS>get-random -input 1, 2, 3, 5, 8, 13 -count ([int]::MaxValue)

2
3
5
1
8
13

Description
-----------
This command returns the entire collection in random order. The value of the Count parameter is the MaxValue static property of integers.

To return an entire collection in random order, enter any number that is greater than or equal to the number of objects in the collection.

Example 8

C:\PS>get-random -input "red", "yellow", "blue"

yellow

Description
-----------
This command returns a random value from a non-numeric collection.

Example 9

C:\PS>get-process | get-random

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    144       4     2080        488    36     0.48   3164 wmiprvse

Description
-----------
This command gets a randomly selected process from the collection of processes on the computer.

Example 10

C:\PS>get-content servers.txt | get-random -count (get-content servers.txt).count | foreach {invoke-expression -computer $_ -command 'get-process powershell'}

This command runs a command on a series of remote computers in random order.

Example 11

C:\PS>get-random -max 100 -setseed 23

# Commands with the default seed are pseudorandom
PS C:\ps-test> get-random -max 100
59
PS C:\ps-test> get-random -max 100
65
PS C:\ps-test> get-random -max 100
21

# Commands with the same seed are not random
PS C:\ps-test> get-random -max 100 -setseed 23
74
PS C:\ps-test> get-random -max 100 -setseed 23
74
PS C:\ps-test> get-random -max 100 -setseed 23
74

# SetSeed results in a repeatable series
PS C:\ps-test> get-random -max 100 -setseed 23
74
PS C:\ps-test> get-random -max 100
56
PS C:\ps-test> get-random -max 100
84
PS C:\ps-test> get-random -max 100
46
PS C:\ps-test> get-random -max 100 -setseed 23
74
PS C:\ps-test> get-random -max 100
56
PS C:\ps-test> get-random -max 100
84
PS C:\ps-test> get-random -max 100
46

Description
-----------
This example shows the effect of using the SetSeed parameter. Because SetSeed produces non-random behavior, it is typically used only to reproduce results, such as when debugging or analyzing a script.

Example 12

C:\PS>$files = dir -path c:\* -recurse

C:\PS> $sample = $files | get-random -count 50

These commands get a randomly selected sample of 50 files from the C: drive of the local computer.

Example 13

C:\PS>get-random 10001

7600

Description
-----------
This command gets a random integer less than 10001. Because the Maximum parameter has position 1, you can omit the parameter name when the value is the first or only unnamed parameter in the command.


Get-Service

Gets the services on a local or remote computer.

Syntax

Get-Service [[-Name] <string[]>] [-ComputerName <string[]>] [-DependentServices] [-Exclude <string[]>] [-Include <string[]>] [-RequiredServices] [<CommonParameters>]

Get-Service -DisplayName <string[]> [-ComputerName <string[]>] [-DependentServices] [-Exclude <string[]>] [-Include <string[]>] [-RequiredServices] [<CommonParameters>]

Get-Service [-InputObject <ServiceController[]>] [-ComputerName <string[]>] [-DependentServices] [-Exclude <string[]>] [-Include <string[]>] [-RequiredServices] [<CommonParameters>]

Description

The Get-Service cmdlet gets objects that represent the services on a local computer or on a remote computer, including running and stopped services.

You can direct Get-Service to get only particular services by specifying the service name or display name of the services, or you can pipe service objects to Get-Service.

Parameters

-ComputerName <string[]>

Gets the services running on the specified computers. The default is the local computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-Service even if your computer is not configured to run remote commands.

Required? | false
Position? | named
Default Value | Localhost
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-DependentServices

Gets only the services that depend upon the specified service.

By default, Get-Service gets all services.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DisplayName <string[]>

Specifies the display names of services to be retrieved. Wildcards are permitted. By default, Get-Service gets all services on the computer.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Retrieves only the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ServiceController[]>

Specifies ServiceController objects representing the services to be retrieved. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe a service object to Get-Service.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the service names of services to be retrieved. Wildcards are permitted. By default, Get-Service gets all of the services on the computer.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | true

-RequiredServices

Gets only the services that this service requires.

This parameter gets the value of the ServicesDependedOn property of the service. By default, Get-Service gets all services.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.ServiceProcess.ServiceController, System.String You can pipe a service object or a service name to Get-Service.
Outputs | System.ServiceProcess.ServiceController Get-Service returns objects that represent the services on the computer.

Notes

You can also refer to Get-Service by its built-in alias, "gsv". For more information, see about_Aliases.

Get-Service can display services only when the current user has permission to see them. If Get-Service does not display services, you might not have permission to see them.

To find the service name and display name of each service on your system, type "get-service". The service names appear in the Name column, and the display names appear in the DisplayName column.

When you sort in ascending order by status value, "Stopped" services appear before "Running" services. The Status property of a service is an enumerated value in which the names of the statuses represent integer values. The sort is based on the integer value, not the name. "Running" appears before "Stopped" because "Stopped" has a value of "1", and "Running" has a value of "4".

Example 1

C:\PS>get-service

This command retrieves all of the services on the system. It behaves as though you typed "get-service *". The default display shows the status, service name, and display name of each service.

Example 2

C:\PS>get-service wmi*

This command retrieves services with service names that begin with "WMI" (the acronym for Windows Management Instrumentation).

Example 3

C:\PS>get-service -displayname *network*

This command displays services with a display name that includes the word
"network". Searching the display name finds network-related services even when the service name does not include "Net", such as xmlprov, the Network Provisioning Service.

Example 4

C:\PS>get-service -name win* -exclude winrm

These commands get only the services with service names that begin with "win", except for the WinRM service.

Example 5

C:\PS>get-service | where-object {$_.Status -eq "Running"}

This command displays only the services that are currently running. It uses the Get-Service cmdlet to get all of the services on the computer. The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects only the services with a Status property that equals "Running".

Status is only one property of service objects. To see all of the properties, type "get-service | get-member".

Example 6

C:\PS>get-service -computername Server02

This command gets the services on the Server02 remote computer.

Because the ComputerName parameter of Get-Service does not use Windows PowerShell remoting, you can use this parameter even if the computer is not configured for remoting in Windows PowerShell.

Example 7

C:\PS>get-service | where-object {$_.DependentServices} | format-list -property Name, DependentServices, @{Label="NoOfDependentS
ervices"; Expression={$_.dependentservices.count}}

Name                  : AudioEndpointBuilder
DependentServices     : {AudioSrv}
NoOfDependentServices : 1

Name                  : Dhcp
DependentServices     : {WinHttpAutoProxySvc}
NoOfDependentServices : 1
...

Description
-----------
These commands list the services on the computer that have dependent services.

The first command uses the Get-Service cmdlet to get the services on the computer. A pipeline operator (|) sends the services to the Where-Object cmdlet, which selects the services whose DependentServices property is not null.

Another pipeline operator sends the results to the Format-List cmdlet. The command uses its Property parameter to display the name of the service, the name of the dependent services, and a calculated property that displays the number of dependent services that each service has.

Example 8

C:\PS>C:\PS> get-service s* | sort-object status

Status   Name               DisplayName
------   ----               -----------
Stopped  stisvc             Windows Image Acquisition (WIA)
Stopped  SwPrv              MS Software Shadow Copy Provider
Stopped  SysmonLog          Performance Logs and Alerts
Running  Spooler            Print Spooler
Running  srservice          System Restore Service
Running  SSDPSRV            SSDP Discovery Service
Running  ShellHWDetection   Shell Hardware Detection
Running  Schedule           Task Scheduler
Running  SCardSvr           Smart Card
Running  SamSs              Security Accounts Manager
Running  SharedAccess       Windows Firewall/Internet Connectio...
Running  SENS               System Event Notification
Running  seclogon           Secondary Logon

C:\PS> get-service s* | sort-object status -descending

Status   Name               DisplayName
------   ----               -----------
Running  ShellHWDetection   Shell Hardware Detection
Running  SharedAccess       Windows Firewall/Internet Connectio...
Running  Spooler            Print Spooler
Running  SSDPSRV            SSDP Discovery Service
Running  srservice          System Restore Service
Running  SCardSvr           Smart Card
Running  SamSs              Security Accounts Manager
Running  Schedule           Task Scheduler
Running  SENS               System Event Notification
Running  seclogon           Secondary Logon
Stopped  SysmonLog          Performance Logs and Alerts
Stopped  SwPrv              MS Software Shadow Copy Provider
Stopped  stisvc             Windows Image Acquisition (WIA)

Description
-----------
This command shows that when you sort services in ascending order by the value of their Status property, stopped services appear before running services. This happens because the value of Status is an enumeration, in which "Stopped" has a value of "1", and "Running" has a value of 4.

To list running services first, use the Descending parameter of the Sort-Object cmdlet.

Example 9

C:\PS>get-service -name winrm -computername localhost, Server01, Server02  | format-table -property MachineName, Status, Name, DisplayName -auto

MachineName    Status  Name  DisplayName
------------   ------  ----  -----------
localhost      Running WinRM Windows Remote Management (WS-Management)
Server01       Running WinRM Windows Remote Management (WS-Management)
Server02       Running WinRM Windows Remote Management (WS-Management)

Description
-----------
This command uses the Get-Service cmdlet to run a "Get-Service Winrm" command on two remote computers and the local computer ("localhost").

The Get-Service command runs on the remote computers, and the results are returned to the local computer. A pipeline operator (|) sends the results to the Format-Table cmdlet, which formats the services as a table. The Format-Table command uses the Property parameter to specify the properties displayed in the table, including the MachineName property.

Example 10

C:\PS>get-service winrm -requiredServices

This command gets the services that the WinRM service requires.

The command returns the value of the ServicesDependedOn property of the service.

Example 11

C:\PS>"winrm" | get-service

This command gets the WinRM service on the local computer. This example shows that you can pipe a service name string (enclosed in quotation marks) to Get-Service.

See Also

  • Start-Service
  • Stop-Service
  • Restart-Service
  • Resume-Service
  • Suspend-Service
  • Set-Service
  • New-Service


Get-TraceSource

Gets the Windows PowerShell components that are instrumented for tracing.

Syntax

Get-TraceSource [[-Name] <string[]>] [<CommonParameters>]

Description

The Get-TraceSource cmdlet gets the trace sources for Windows PowerShell components that are currently in use. You can use the data to determine which Windows PowerShell components you can trace. When tracing, the component generates detailed messages about each step in its internal processing. Developers use the trace data to monitor data flow, program execution, and errors. The tracing cmdlets were designed for Windows PowerShell developers, but they are available to all users.

Parameters

-Name <string[]>

Gets only the specified trace sources. Wildcards are permitted. The parameter name ("Name") is optional.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains the name of a trace source to Get-TraceSource.
Outputs | System.Management.Automation.PSTraceSource Get-TraceSource returns objects that represent the trace sources.

Example 1

C:\PS>get-traceSource  *provider*

This command gets all of the trace sources that have names that include "provider".

Example 2

C:\PS>get-tracesource

This command gets all of the Windows PowerShell components that can be traced.

See Also

  • Set-TraceSource
  • Trace-Command


Get-Transaction

Gets the current (active) transaction.

Syntax

Get-Transaction [<CommonParameters>]

Description

The Get-Transaction cmdlet gets an object that represents the current transaction in the session.

This cmdlet never returns more than one object, because only one transaction is active at a time. If you start one or more independent transactions (by using the Independent parameter of Start-Transaction), the most recently started transaction is active, and that is the transaction that Get-Transaction returns.

When all active transactions have either been rolled back or committed, Get-Transaction shows the transaction that was most recently active in the session.

The Get-Transaction cmdlet is one of a set of cmdlets that support the transactions feature in Windows PowerShell. For more information, see about_Transactions.

Parameters

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to this cmdlet.
Outputs | System.Management.Automation.PSTransaction Get-Transaction returns an object that represents the current transaction.

Example 1

C:\PS>start-transaction

C:\PS> get-transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   ------
Error                1                 Active

Description
-----------
This command uses the Get-Transaction cmdlet to get the current transaction.

Example 2

C:\PS>get-transaction | get-member

Name               MemberType Definition
----               ---------- ----------
Dispose            Method     System.Void Dispose(), System.Void Dispose(Boolean disposing)
Equals             Method     System.Boolean Equals(Object obj)
GetHashCode        Method     System.Int32 GetHashCode()
GetType            Method     System.Type GetType()
ToString           Method     System.String ToString()
IsCommitted        Property   System.Boolean IsCommitted {get;}
IsRolledBack       Property   System.Boolean IsRolledBack {get;}
RollbackPreference Property   System.Management.Automation.RollbackSeverity RollbackPreference {get;}
SubscriberCount    Property   System.Int32 SubscriberCount {get;set;}

Description
-----------
This command uses the Get-Member cmdlet to show the properties and methods of the transaction object.

Example 3

C:\PS>cd hklm:\software
HKLM:\SOFTWARE> Start-Transaction
HKLM:\SOFTWARE> New-Item MyCompany -UseTransaction
HKLM:\SOFTWARE> Undo-Transaction
HKLM:\SOFTWARE> Get-Transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   ----------
Error                0                 RolledBack

Description
-----------
This command shows the property values of a transaction object for a transaction that has been rolled back.

Example 4

C:\PS>cd hklm:\software
HKLM:\SOFTWARE> Start-Transaction
HKLM:\SOFTWARE> New-Item MyCompany -UseTransaction
HKLM:\SOFTWARE> Complete-Transaction
HKLM:\SOFTWARE> Get-Transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   ---------
Error                1                 Committed

Description
-----------
This command shows the property values of a transaction object for a transaction that has been committed.

Example 5

C:\PS>cd hklm:\software
HKLM:\SOFTWARE> Start-Transaction
HKLM:\SOFTWARE> New-Item MyCompany -UseTransaction

HKLM:\SOFTWARE> Start-Transaction
HKLM:\SOFTWARE> New-Item MyCompany2 -UseTransaction

HKLM:\SOFTWARE> Get-Transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   ------
Error                2                 Active

HKLM:\SOFTWARE> Complete-Transaction
HKLM:\SOFTWARE> Get-Transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   ------
Error                1                 Active

HKLM:\SOFTWARE> Complete-Transaction
HKLM:\SOFTWARE> Get-Transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   ---------
Error                1                 Committed

Description
-----------
This example shows the effect on the transaction object of starting a transaction while another transaction is in progress. Typically, this happens when a script that runs a transaction includes a function or calls a script that contains another complete transaction.

Unless the second Start-Transaction command includes the Independent parameter, Start-Transaction does not create a new transaction. Instead, it adds a second subscriber to the original transaction.

The first Start-Transaction command starts the transaction. A New-Item command with the UseTransaction parameter is part of the transaction.

A second Start-Transaction command adds a subscriber to the transaction. The next New-Item command is also part of the transaction.

The first Get-Transaction command shows the multi-subscriber transaction. Notice that the subscriber count is 2.

The first Complete-Transaction command does not commit the transaction, but it reduces the subscriber count to 1.

The second Complete-Transaction command commits the transaction.

Example 6

C:\PS>HKLM:\SOFTWARE> Start-Transaction

HKLM:\SOFTWARE> Get-Transaction

RollbackPreference   SubscriberCount   IsRolledBack   IsCommitted
------------------   ---------------   ------------   -----------
Error                1                 False          False

HKLM:\SOFTWARE> Start-Transaction -Independent
HKLM:\SOFTWARE> Get-Transaction

RollbackPreference   SubscriberCount   IsRolledBack   IsCommitted
------------------   ---------------   ------------   -----------
Error                1                 False          False

HKLM:\SOFTWARE> Complete-Transaction
HKLM:\SOFTWARE> Get-Transaction

HKLM:\SOFTWARE> Complete-Transaction
HKLM:\SOFTWARE> Get-Transaction

Description
-----------
This example shows the effect on the transaction object of starting an independent transaction while another transaction is in progress.

The first Start-Transaction command starts the transaction. A New-Item command with the UseTransaction parameter is part of the transaction.

A second Start-Transaction command adds a subscriber to the transaction. The next New-Item command is also part of the transaction.

The first Get-Transaction command shows the multi-subscriber transaction. Note that the subscriber count is 2.

The Complete-Transaction command reduces the subscriber count to 1, but it does not commit the transaction.

The second Complete-Transaction command commits the transaction.

See Also

  • about_Transactions
  • about_Providers
  • Start-Transaction
  • Complete-Transaction
  • Undo-Transaction
  • Use-Transaction


Get-UICulture

Gets the current user interface (UI) culture settings in the operating system.

Syntax

Get-UICulture [<CommonParameters>]

Description

The Get-UICulture cmdlet gets information about the current UI culture settings for Windows. The UI culture determines which text strings are used for user interface elements, such as menus and messages.

You can also use the Get-Culture cmdlet, which gets the current culture on the system. The culture determines the display format of items such as numbers, currency, and dates.

Parameters

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Globalization.CultureInfo Get-UICulture returns an object that represents the current UI culture.

Notes

You can also use the $PsCulture and $PsUICulture variables. The $PsCulture variable stores the name of the current culture, and the $PsUICulture variable stores the name of the current UI culture.

Example 1

C:\PS>get-uiculture

This command gets the current UI culture information.

Example 2

C:\PS>get-uiculture | format-list *

This command displays the values of all of the properties of the current UI culture in a list.

Example 3

C:\PS>(get-uiculture).calendar

This command displays the current values for the Calendar property of the current UI culture. Calendar is just one property of UI culture. To see all of the properties, type "get-uiculture | get-member".

Example 4

C:\PS>(get-uiculture).datetimeformat.shortdatepattern

This command displays the short date pattern for the current UI culture. To see all of the subproperties of the DateTimeFormat property of the UI culture, type "(get-uiculture).datetimeformat | gm".


Get-Unique

Returns the unique items from a sorted list.

Syntax

Get-Unique [-AsString] [-InputObject <psobject>] [<CommonParameters>]

Get-Unique [-OnType] [-InputObject <psobject>] [<CommonParameters>]

Description

The Get-Unique cmdlet compares each item in a sorted list to the next item, eliminates duplicates, and returns only one instance of each item. The list must be sorted for the cmdlet to work properly.

Parameters

-AsString

Treats the data as a string. Without this parameter, data is treated as an object, so when you submit a collection of objects of the same type to Get-Unique, such as a collection of files, it returns just one (the first). You can use this parameter to find the unique values of object properties, such as the file names.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Accepts input for Get-Unique. Enter a variable that contains the objects or type a command or expression that gets the objects.

Get-Unique treats the input submitted by using InputObject as a collection; it does not enumerate individual items in the collection. Because the collection is a single item, input submitted by using InputObject is always returned unchanged.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-OnType

Returns only one object of each type.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any type of object to Get-Unique.
Outputs | System.Management.Automation.PSObject The type of object that Get-Unique returns is determined by the input.

Notes

You can also refer to Get-Unique by its built-in alias, "gu". For more information, see about_Aliases.

To sort a list, use Sort-Object. You can also use the Unique parameter of Sort-Object to find the unique items in a list.

Example 1

C:\PS>$a = $(foreach ($line in get-content C:\Test1\File1.txt) {$line.tolower().split(" ")}) | sort | get-unique

C:\PS> $a.count

These commands find the number of unique words in a text file.

The first command gets the content of the File.txt file. It converts each line of text to lowercase letters and then splits each word onto a separate line at the space (" "). Then, it sorts the resulting list alphabetically (the default) and uses the Get-Unique cmdlet to eliminate any duplicate words. The results are stored in the $a variable.

The second command uses the Count property of the collection of strings in $a to determine how many items are in $a.

Example 2

C:\PS>1,1,1,1,12,23,4,5,4643,5,3,3,3,3,3,3,3 | sort-object | Get-Unique

This command finds the unique members of the set of integers. The first command takes an array of integers typed at the command line, pipes them to the Sort-Object cmdlet to be sorted, and then pipes them to Get-Unique, which eliminates duplicate entries.

Example 3

C:\PS>get-childitem | sort-object {$_.GetType()} |  unique -OnType

This command uses the Get-ChildItem cmdlet to retrieve the contents of the local directory, which includes files and directories. The pipeline operator (|) sends the results to the Sort-Object cmdlet. The "$_.GetType()" statement applies the GetType method to each file or directory. Then, Sort-Object sorts the items by type. Another pipeline operator sends the results to Get-Unique. The OnType parameter directs Get-Unique to return only one object of each type.

Example 4

C:\PS>get-process | sort-object | select processname | get-unique -asstring

This command gets the names of processes running on the computer with duplicates eliminated.

The Get-Process command gets all of the processes on the computer. The pipeline operator (|) passes the result to Sort-Object, which, by default, sorts the processes alphabetically by ProcessName. The results are piped to the Select-Object cmdlet, which selects only the values of the ProcessName property of each object. The results are then piped to Get-Unique to eliminate duplicates.

The AsString parameter tells Get-Unique to treat the ProcessName values as strings. Without this parameter, Get-Unique treats the ProcessName values as objects and returns only one instance of the object, that is, the first process name in the list.

See Also

  • Select-Object
  • Sort-Object


Get-Variable

Gets the variables in the current console.

Syntax

Get-Variable [[-Name] <string[]>] [-Exclude <string[]>] [-Include <string[]>] [-Scope <string>] [-ValueOnly] [<CommonParameters>]

Description

The Get-Variable cmdlet gets the Windows PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name.

Parameters

-Exclude <string[]>

Omits the specified items. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Specifies only the items upon which the cmdlet will act, excluding all others. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the name of the variable.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Scope <string>

Gets only the variables in the specified scope. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ValueOnly

Gets only the value of the variable.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains the variable name to Get-Variable.
Outputs | Variable object Get-Variable returns a System.Management.Automation variable object for each variable that it gets. The object type depends on the variable.

Notes

This cmdlet does not manage environment variables. To manage environment variables, you can use the environment Variable Provider.

Example 1

C:\PS>get-variable m*

This command displays variables with names that begin with the letter "m". The value of the variables is also displayed.

Example 2

C:\PS>get-variable m* -valueonly

This command displays only the values of the variables with names that begin with the letter "m".

Example 3

C:\PS>get-variable -include M*,P* | sort-object name

This command gets information about the variables that begin with either the letter "M" or the letter "P". The results are piped to the Sort-Object cmdlet, sorted by name, and displayed.

Example 4

C:\PS>get-variable -scope 0

C:\PS> compare-object (get-variable -scope 0) (get-variable -scope 1)

The first command gets only the variables that are defined in the local scope. It is equivalent to "get-variable -scope local" and can be abbreviated as "gv -s 0".

The second command uses the Compare-Object cmdlet to find the variables that are defined in the parent scope (Scope 1) but are visible only in the local scope (Scope 0).

See Also

  • Set-Variable
  • New-Variable
  • Clear-Variable
  • Remove-Variable


Get-WinEvent

Gets events from event logs and event tracing log files on local and remote computers.

Syntax

Get-WinEvent [-LogName] <string[]> [-ComputerName <string>] [-Credential <PSCredential>] [-FilterXPath <string>] [-Force <switch>] [-MaxEvents <int64>] [-Oldest] [<CommonParameters>]

Get-WinEvent [-Path] <string[]> [-ComputerName <string>] [-Credential <PSCredential>] [-FilterXPath <string>] [-Force <switch>] [-MaxEvents <int64>] [-Oldest] [<CommonParameters>]

Get-WinEvent [-ProviderName] <string[]> [-ComputerName <string>] [-Credential <PSCredential>] [-FilterXPath <string>] [-Force <switch>] [-MaxEvents <int64>] [-Oldest] [<CommonParameters>]

Get-WinEvent -FilterHashTable <Hashtable[]> [-ComputerName <string>] [-Credential <PSCredential>] [-Force <switch>] [-MaxEvents <int64>] [-Oldest] [<CommonParameters>]

Get-WinEvent [-ListLog] <string[]> [-ComputerName <string>] [-Credential <PSCredential>] [<CommonParameters>]

Get-WinEvent [-ListProvider] <string[]> [-ComputerName <string>] [-Credential <PSCredential>] [<CommonParameters>]

Get-WinEvent -FilterXml <XmlDocument> [-ComputerName <string>] [-Credential <PSCredential>] [-Force <switch>] [-MaxEvents <int64>] [-Oldest] [<CommonParameters>]

Description

The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs, and the event logs that are generated by the new Windows Event Log technology introduced in Windows Vista. It also gets events in log files generated by Event Tracing for Windows (ETW).

Without parameters, a Get-WinEvent command gets all the events from all the event logs on the computer. To interrupt the command, press CTRL + C.

Get-WinEvent also lists event logs and event log providers. You can get events from selected logs or from logs generated by selected event providers. And, you can combine events from multiple sources in a single command. Get-WinEvent allows you to filter events by using XPath queries, structured XML queries, and simplified hash-table queries.

Note: Get-WinEvent requires Windows Vista, Windows Server 2008 R2, or later versions of Windows. And, it requires the Microsoft .NET Framework 3.5 or a later version.

Parameters

-ComputerName <string>

Gets events from the event logs on the specified computer. Type the NetBIOS name, an Internet Protocol (IP) address, or the fully qualified domain name of the computer. The default value is the local computer.

This parameter accepts only one computer name at a time. To find event logs or events on multiple computers, use a ForEach statement. For more information about this parameter, see the examples.

To get events and event logs from remote computers, the firewall port for the event log service must be configured to allow remote access.

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter even if your computer is not configured to run remote commands.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default value is the current user.

Type a user name, such as User01 or Domain01\User01. Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password. If you type only the parameter name, you will be prompted for both a user name and a password.

Required? | false
Position? | named
Default Value | Current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilterHashTable <Hashtable[]>

Uses a query in hash table format to select events from one or more event logs. The query contains a hash table with one or more key-value pairs.

Hash table queries have the following rules:

-- Keys and values are case-insensitive.

-- Wildcard characters are valid only in the values associated with the LogName and ProviderName keys.

-- Each key can be listed only once in each hash-table.

-- The Path value takes paths to .etl, .evt, and .evtx log files.

-- The LogName, Path, and ProviderName keys can be used in the same query.

-- The UserID key can take a valid security identifier (SID) or a domain account name that can be used to construct a valid System.Security.Principal.NTAccount object.

-- The Data value takes event data in an unnamed field. This is for events in classic event logs.

-- The * key represents a named event data field.

When Get-WinEvent cannot interpret a key-value pair, it interprets the key as a case-sensitive name for the event data in the event.

The valid key-value pairs are as follows:

-- LogName=<String[]>

-- ProviderName=<String[]>

-- Path=<String[]>

-- Keywords=<Long[]>

-- ID=<Int32[]>

-- Level=<Int32[]>

-- StartTime=<DateTime>

-- EndTime=<DataTime>

-- UserID=<SID>

-- Data=<String[]>

-- *=<String[]>

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-FilterXml <XmlDocument>

Uses a structured XML query to select events from one or more event logs.

To generate a valid XML query, use the Create Custom View and Filter Current Log features in Event Viewer. Use the items in the dialog box to create a query, and then click the XML tab to view the query in XML format. You can copy the XML from the XML tab into the value of the FilterXml parameter. For more information about the Event Viewer features, see Event Viewer Help.

Typically, you use an XML query to create a complex query that contains several XPath statements. The XML format also allows you to use a "Suppress" XML element that excludes events from the query. For more information about the XML schema for event log queries, see the following topics in the MSDN (Microsoft Developer Network) library.

-- "Query Schema": http://go.microsoft.com/fwlink/?LinkId=143685

-- "XML Event Queries" in "Event Selection": http://go.microsoft.com/fwlink/?LinkID=143608

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-FilterXPath <string>

Uses an XPath query to select events from one or more logs.

For more information about the XPath language, see "Selection Filters" in "Event Selection" and in the "XPath Reference" in the MSDN library.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force <switch>

Gets debug and analytic logs, in addition to other event logs. The Force parameter is required to get a debug or analytic log when the value of the name parameter includes wildcard characters.

By default, Get-WinEvent excludes these logs unless you specify the full name of a debug or analytic log.

Required? | false
Position? | named
Default Value | Debugging and analytic logs are not returned in response to queries that use wildcard characters.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ListLog <string[]>

Gets the specified event logs. Enter the event log names in a comma-separated list. Wildcards are permitted. To get all the logs, enter a value of *.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-ListProvider <string[]>

Gets the specified event log providers. An event log provider is a program or service that writes events to the event log.

Enter the provider names in a comma-separated list. Wildcards are permitted. To get the providers of all the event logs on the computer, enter a value of *.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-LogName <string[]>

Gets events from the specified event logs. Enter the event log names in a comma-separated list. Wildcards are permitted. You can also pipe log names to Get-WinEvent.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | true

-MaxEvents <int64>

Specifies the maximum number of events that Get-WinEvent returns. Enter an integer. The default is to return all the events in the logs or files.

Required? | false
Position? | named
Default Value | All events
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Oldest

Returns the events in oldest-first order. By default, events are returned in newest-first order.

This parameter is required to get events from .etl and .evt files and from debug and analytic logs. In these files, events are recorded in oldest-first order, and the events can be returned only in oldest-first order.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Gets events from the specified event log files. Enter the paths to the log files in a comma-separated list, or use wildcard characters to create file path patterns.

Get-WinEvent supports files with the .evt, .evtx, and .etl file name extensions. You can include events from different files and file types in the same command.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-ProviderName <string[]>

Gets events written by the specified event log providers. Enter the provider names in a comma-separated list, or use wildcard characters to create provider name patterns.

An event log provider is a program or service that writes events to the event log. It is not a Windows PowerShell provider.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs

System.String, System.Xml.XmlDocument, System.Collections.Hashtable.

You can pipe a LogName (string), a FilterXML query, or a FilterHashTable query to Get-WinEvent.

Outputs

System.Diagnostics.Eventing.Reader.EventLogConfiguration, System.Diagnostics.Eventing.Reader.EventLogRecord, System.Diagnostics.Eventing.Reader.ProviderMetadata

With the ListLog parameter, Get-WinEvent returns System.Diagnostics.Eventing.Reader.EventLogConfiguration objects. With the ListProvider parameter, Get-WinEvent returns System.Diagnostics.Eventing.Reader.ProviderMetadata objects. With all other parameters, Get-WinEvent returns System.Diagnostics.Eventing.Reader.EventLogRecord objects.

Notes

Get-WinEvent is designed to replace the Get-EventLog cmdlet on computers running Windows Vista and later versions of Windows. Get-EventLog gets events only in classic event logs. Get-EventLog is retained in Windows PowerShell 2.0 for systems earlier than Windows Vista.

Example 1

C:\PS>get-winevent -listlog  *

This command gets all the logs on the local computer.

Logs are listed in the order that Get-WinEvent gets them. Classic logs are usually retrieved first, followed by the new Windows Eventing logs.

Because there are typically more than a hundred event logs, this parameter requires a log name or name pattern. To get all the logs, use *.

Example 2

C:\PS>get-winevent -listlog Setup | format-list -property *

FileSize                       : 69632
    IsLogFull                      : False
    LastAccessTime                 : 2/14/2008 12:55:12 AM
    LastWriteTime                  : 7/9/2008 3:12:05 AM
    OldestRecordNumber             : 1
    RecordCount                    : 3
    LogName                        : Setup
    LogType                        : Operational
    LogIsolation                   : Application
    IsEnabled                      : True
    IsClassicLog                   : False
    SecurityDescriptor             : O:BAG:SYD:(A;;0xf0007;;;SY)(A;
                                     (A;;0x1;;;S-1-5-32-573)
    LogFilePath                    : %SystemRoot%\System32\Winevt\L
    MaximumSizeInBytes             : 1052672
    LogMode                        : Circular
    OwningProviderName             : Microsoft-Windows-Eventlog
    ProviderNames                  : {Microsoft-Windows-WUSA, Micro
    ProviderLevel                  :
    ProviderKeywords               :
    ProviderBufferSize             : 64
    ProviderMinimumNumberOfBuffers : 0
    ProviderMaximumNumberOfBuffers : 64
    ProviderLatency                : 1000
    ProviderControlGuid            :

Description
-----------
These commands get an object that represents the classic System log on the local computer. The object includes useful information about the log, including its size, event log provider, file path, and whether it is enabled.

Example 3

C:\PS>get-winevent -listlog * -computername Server01| where {$_.recordcount}

This command gets only event logs on the Server01 computer that contain events. Many logs might be empty.

The command uses the RecordCount property of the EventLogConfiguration object that Get-WinEvent returns when you use the ListLog parameter.

Example 4

C:\PS>$s = "Server01", "Server02", "Server03"

C:\PS> foreach ($server in $s)
     {$server; get-winevent -listlog "Windows PowerShell" -computername $server}

The commands in this example get objects that represent the Windows PowerShell event logs on the Server01, Server02, and Server03 computers. This command uses the Foreach keyword because the ComputerName parameter takes only one value.

The first command saves the names of the computers in the $s variable.

The second command uses a Foreach statement. For each of the computers in the $s variable, it performs the command in the script block (within the braces). First, the command prints the name of the computer. Then, it runs a Get-WinEvent command to get an object that represents the Windows PowerShell log.

Example 5

C:\PS>get-winevent -listprovider *

This command gets the event log providers on the local computer and the logs to which they write, if any.

Example 6

C:\PS>(get-winevent -listlog Application).providernames

This command gets all of the providers that write to the Application log on the local computer.

Example 7

C:\PS>>get-winevent -listprovider *policy*

This command gets the event log providers whose names include the word "policy."

Example 8

C:\PS>(get-winevent -listprovider microsoft-windows-grouppolicy).events | format-table id, description -auto

This command lists the event IDs that the Microsoft-Windows-GroupPolicy event provider generates along with the event description.

It uses the Events property of the object that Get-WinEvent returns when you use the ListProvider parameter, and it uses the ID and Description properties of the object in the Events property.

Example 9

C:\PS>$events = get-winevent -logname "Windows PowerShell"

C:\PS> $events.count
195

C:\PS> $events | group-object id -noelement | sort-object count -desc
Count Name
----- ----
  147 600
   22 400
   21 601
    3 403
    2 103

 C:\PS> $events | group-object leveldisplayname -noelement
Count Name
----- ----
    2 Warning
  193 Information

Description
-----------
This example shows how to use the properties of the event objects that Get-WinEvent returns to learn about the events in an event log.

The first command uses the Get-WinEvent cmdlet to get all of the events in the Windows PowerShell event log. Then, it saves them in the $events variable. The log name is enclosed in quotation marks because it contains a space.

The second command uses the Count property of object collections to find the number of entries in the event log.

The third command displays the incidence of each event in the log, with the most frequent events first. In this example, event ID 600 is the most frequent event.

The fourth command groups the items by the value of their LevelDisplayName property to show how many Error, Warning, and Information events are in the log.

Example 10

C:\PS>get-winevent -logname *disk*, Microsoft-Windows-Kernel-WHEA

This command gets the error events whose names include "disk" from all of the event logs on the computer and from the Microsoft-Windows-Kernel-WHEA event log.

Example 11

C:\PS>get-winevent -path 'c:\ps-test\Windows PowerShell.evtx'

This command gets events from a copy of the Windows PowerShell event log file in a test directory. The path is enclosed in quotation marks because the log name includes a space.

Example 12

C:\PS>get-winevent -path 'c:\tracing\tracelog.etl' -maxevents 100 -oldest

C:\PS> get-winevent -path 'c:\tracing\tracelog.etl' -oldest | sort-object -property timecreated -desc | select-object -first 100

These commands get the first 100 events from an Event Tracing for Windows (ETW) event trace log file.

The first command gets the 100 oldest events in the log. It uses the Get-WinEvent cmdlet to get events from the Tracelog.etl file. It uses the MaxEvents parameter to limit the retrieval to 100 events. Because the events are listed in the order in which they are written to the log (oldest first), the Oldest parameter is required.

The second command gets the 100 newest events in the log. It uses the Get-WinEvent cmdlet to get all the events from the Tracing.etl file. It passes
the events to the Sort-Object cmdlet, which sorts them in descending order by the value of the TimeCreated property. Then, it sends the sorted events to the Select-Object cmdlet to select the newest 100 events.

Example 13

C:\PS>get-winevent -path "c:\tracing\tracelog.etl", "c:\Logs\Windows PowerShell.evtx" -oldest | where {$_.id -eq "103"}

This example shows how to get the events from an event trace log file (.etl) and from a copy of the Windows PowerShell log file (.evtx) that was saved to a test directory.

You can combine multiple file types in a single command. Because the files contain the same type of .NET Framework object (an EventLogRecord object), you can use the same properties to filter them.

Note that the command requires the Oldest parameter because it is reading from an .etl file, but the Oldest parameter applies to both of the files.

Example 14

C:\PS># Use the Where-Object cmdlet
C:\PS> $yesterday = (get-date) - (new-timespan -day 1)
C:\PS> get-winevent -logname "Windows PowerShell" | where {$_.timecreated -ge $yesterday}

# Uses FilterHashTable
C:\PS> $yesterday = (get-date) - (new-timespan -day 1)
C:\PS> get-winevent -FilterHashTable @{LogName='Windows PowerShell'; Level=3; StartTime=$yesterday}

# Use FilterXML
C:\PS> get-winevent -FilterXML "<QueryList><Query><Select Path='Windows PowerShell'>*[System[Level=3 and TimeCreated[timediff(@SystemTime) <= 86400000]]]</Select></Query></QueryList>"

# Use FilterXPath
C:\PS> get-winevent -LogName "Windows Powershell" -FilterXPath "*[System[Level=3 and TimeCreated[timediff(@SystemTime) <= 86400000]]]"

This example shows different filtering methods for selecting events from an event log. All of these commands get events that occurred in the last 24 hours from the Windows PowerShell event log.

The filter methods are more efficient than using the Where-Object cmdlet because the filters are applied while the objects are being retrieved, rather than retrieving all the objects and then filtering them.

Because dates are difficult to formulate in the XML and XPath formats, to create the XML content for the date, the Filter Current Log feature of Event Viewer is used. For more information about this feature, see Event Viewer Help.

Example 15

C:\PS>$date = (get-date).AddDays(-2)

C:\PS> $events = get-winevent -FilterHashTable @{ logname = "Microsoft-Windows-Diagnostics-Performance/Operational"; StartTime = $date; ID = 100 }

This example uses a filter hash table to get events from the performance log.

The first command uses the Get-Date cmdlet and the AddDays method to get a date that is two days before the current date. It saves the date in the $date variable.

The second command uses the Get-WinEvent cmdlet with the FilterHashTable parameter. The keys in the hash table define a filter that selects events from the performance log that occurred within the last two days and that have event ID 100.

The LogName key specifies the event log, the StartTime key specifies the date, and the ID key specifies the event ID.

Example 16

C:\PS>$starttime = (get-date).adddays(-7)

C:\PS> $ie-error = Get-WinEvent -FilterHashtable @{logname="application"; providername="Application Error"; data="iexplore.exe"; starttime=$starttime}

This example uses a filter hash table to find Internet Explorer application errors that occurred within the last week.

The first command gets the date that is seven days before the current date and stores it in the $starttime variable.

The second command uses the Get-WinEvent cmdlet with the FilterHashTable parameter. The keys in the hash table define a filter that selects events from the Application log that were written by the Application Error provider and include the phrase "iexplore.exe".

The LogName key specifies the event log. The ProviderName key specifies the event provider, the StartTime key specifies the starting date of the events, and the Data key specifies the text in the event message.

See Also

  • Get-EventLog
  • Get-Counter
  • about_EventLogs


Get-WmiObject

Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes.

Syntax

Get-WmiObject [-Authority <string>] [-Amended] [-AsJob] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit <int>] [<CommonParameters>]

Get-WmiObject [[-Class] <string>] [-Authority <string>] [-List] [-Recurse] [-Amended] [-AsJob] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit <int>] [<CommonParameters>]

Get-WmiObject [-Authority <string>] [-Amended] [-AsJob] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit <int>] [<CommonParameters>]

Get-WmiObject [-Class] <string> [[-Property] <string[]>] [-Authority <string>] [-DirectRead] [-Filter <string>] [-Amended] [-AsJob] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit <int>] [<CommonParameters>]

Get-WmiObject -Query <string> [-Authority <string>] [-DirectRead] [-Amended] [-AsJob] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit <int>] [<CommonParameters>]

Description

The Get-WmiObject cmdlet gets instances of WMI classes or information about the available WMI classes. The ComputerName parameter can always be used to specify a remote computer. If the List parameter is specified, the cmdlet gets information about the WMI classes that are available in a specified namespace. If the Query parameter is specified, the cmdlet runs a WMI query language (WQL) statement.

The Get-WmiObject cmdlet does not use the Windows PowerShell remoting infrastructure to perform remote operations. You can use the ComputerName parameter of the Get-WmiObject cmdlet even if your computer does not meet the requirements for Windows PowerShell remoting and even if your computer is not configured for remoting in Windows PowerShell.

Parameters

-Amended

Gets or sets a value that indicates whether the objects that are returned from WMI should contain amended information. Typically, amended information is localizable information, such as object and property descriptions, that is attached to the WMI object..

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsJob

Runs the command as a background job. Use this parameter to run commands that take a long time to finish.

When you use the AsJob parameter, the command returns an object that represents the background job and then displays the command prompt. You can continue to work in the session while the job finishes. If Get-WmiObject is used against a remote computer, the job is created on the local computer, and the results from remote computers are automatically returned to the local computer. To manage the job, use the cmdlets that contain the Job noun (the Job cmdlets). To get the job results, use the Receive-Job cmdlet.

Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must start Windows PowerShell by using the "Run as administrator" option in Windows Vista and later versions of Windows,. For more information, see about_Remote_Requirements.

For more information about Windows PowerShell background jobs, see about_Jobs and about_Remote_Jobs.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationLevel>

Specifies the authentication level to be used with the WMI connection. Valid values are:

-1: Unchanged

0: Default

1: None (No authentication in performed.)

2: Connect (Authentication is performed only when the client establishes a relationship with the application.)

3: Call (Authentication is performed only at the beginning of each call when the application receives the request.)

4: Packet (Authentication is performed on all the data that is received from the client.)

5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.)

6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.)

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authority <string>

Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to ntlmdomain:<DomainName>, where <DomainName> identifies a valid NTLM domain name. To use Kerberos, specify kerberos:<DomainName>\<ServerName>". You cannot include the authority setting when you connect to the local computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Class <string>

Specifies the name of a WMI class. When this parameter is used, the cmdlet retrieves instances of the WMI class.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name. This parameter can also be piped to the cmdlet.

This parameter does not rely on Windows PowerShell remoting, which uses WS-Management ). You can use the ComputerName parameter of Get-WmiObject even if your computer is not configured to run WS-Management remote commands.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or User@Contoso.com. Or, enter a PSCredential object, such as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DirectRead

Specifies whether direct access to the WMI provider is requested for the specified class without any regard to its base class or to its derived classes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-EnableAllPrivileges

Enables all the privileges of the current user before the command makes the WMI call.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a Where clause to use as a filter. Uses the syntax of the WMI Query Language (WQL).

Important: Do not include the Where keyword in the value of the parameter. For example, the following commands return only the logical disks that where the DeviceID equals 'c:' and the services where the name equals 'WinRM', without using the Where keyword:

get-WmiObject Win32_LogicalDisk -filter "DeviceID = 'c:' "

get-wmiobject win32_service -filter "name='WinRM'"

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Impersonation <ImpersonationLevel>

Specifies the impersonation level to use. Valid values are:

0: Default (reads the local registry for the default impersonation level , which is usually set to "3: Impersonate".)

1: Anonymous (Hides the credentials of the caller.)

2: Identify (Allows objects to query the credentials of the caller.)

3: Impersonate (Allows objects to use the credentials of the caller.)

4: Delegate (Allows objects to permit other objects to use the credentials of the caller.)

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-List

Specifies whether to retrieve and display the names of the WMI classes in the WMI repository namespace that is specified in the Namespace parameter. The Default Namespace registry entry in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\Scripting registry key is not used by this cmdlet to determine the default namespace. If you specify the List parameter but not the Namespace parameter, the root\CIMV2 namespace is used by default.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Locale <string>

Specifies the preferred locale for WMI objects. Specify the value of the Locale parameter as an array in the MS_<LCID> format in the preferred order .

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Namespace <string>

When used with the Class parameter, this parameter specifies the WMI repository namespace where the referenced WMI class is located. When used with the List parameter, it specifies the namespace from which to gather WMI class information.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Property <string[]>

Specifies the WMI class property or set of properties to retrieve.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Query <string>

Specifies a WMI Query Language (WQL) statement to run. Event queries are not supported by this parameter.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Recurse

Makes the command search the current namespace and all other namespaces for the class name that is specified in the Class parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Allows the user to specify a throttling value for the number of WMI operations that can be executed simultaneously. This parameter is used together with the AsJob parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to Get-WmiObject.
Outputs | PSObject or System.Management.Automation.RemotingJob When you use the AsJob parameter, the cmdlet returns a job object. Otherwise, the object that Get-WmiObject returns depends on the value of the Class parameter.

Notes

To access WMI information on a remote computer, the cmdlet must run under an account that is a member of the local administrators group on the remote computer. Alternatively, the default access control on the WMI namespace of the remote repository can be changed to give other account access rights.

By default, only some of the properties of a WMI class are displayed. The set of properties that will be displayed for each WMI class is specified in the Types.ps1xml configuration file. One of the examples included in this Help topic demonstrates how to override this behavior by using the Format-List cmdlet.

Example 1

C:\PS>get-wmiobject win32_process

__GENUS                    : 2
__CLASS                    : Win32_Process
__SUPERCLASS               : CIM_Process
__DYNASTY                  : CIM_ManagedSystemElement
__RELPATH                  : Win32_Process.Handle="0"
__PROPERTY_COUNT           : 45
__DERIVATION               : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER                   : SYSTEM01
__NAMESPACE                : root\cimv2
__PATH                     : \\SYSTEM01\root\cimv2:Win32_Process.Handle="0"
Caption                    : System Idle Process
CommandLine                :
CreationClassName          : Win32_Process
CreationDate               :
CSCreationClassName        : Win32_ComputerSystem
CSName                     : SYSTEM01
Description                : System Idle Process
ExecutablePath             :
ExecutionState             :
Handle                     : 0
HandleCount                : 0
InstallDate                :
KernelModeTime             : 6138394740432
MaximumWorkingSetSize      :
MinimumWorkingSetSize      :
Name                       : System Idle Process
OSCreationClassName        : Win32_OperatingSystem
OSName                     : Microsoftr Windows VistaT Ultimate |C:\Windows|\Device\Harddisk0\Partition3
OtherOperationCount        : 0
OtherTransferCount         : 0
PageFaults                 : 0
PageFileUsage              : 0
ParentProcessId            : 0
PeakPageFileUsage          : 0
PeakVirtualSize            : 0
PeakWorkingSetSize         : 0
Priority                   : 0
PrivatePageCount           : 0
ProcessId                  : 0
QuotaNonPagedPoolUsage     : 0
QuotaPagedPoolUsage        : 0
QuotaPeakNonPagedPoolUsage : 0
QuotaPeakPagedPoolUsage    : 0
ReadOperationCount         : 0
ReadTransferCount          : 0
SessionId                  : 0
Status                     :
TerminationDate            :
ThreadCount                : 2
UserModeTime               : 0
VirtualSize                : 0
WindowsVersion             : 6.0.6001
WorkingSetSize             : 24576
WriteOperationCount        : 0
WriteTransferCount         : 0
ProcessName                : System Idle Process
Handles                    : 0
VM                         : 0
WS                         : 24576
Path                       :

...

Description
-----------
This command displays information about all the processes that are running on a computer.

Example 2

C:\PS>get-wmiobject win32_service -computername 127.0.0.1

__GENUS                    : 2
__CLASS                    : Win32_Process
__SUPERCLASS               : CIM_Process
__DYNASTY                  : CIM_ManagedSystemElement
__RELPATH                  : Win32_Process.Handle="0"
__PROPERTY_COUNT           : 45
__DERIVATION               : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER                   : SYSTEM02
__NAMESPACE                : root\cimv2
__PATH                     : \\SYSTEM02\root\cimv2:Win32_Process.Handle="0"
Caption                    : System Idle Process
CommandLine                :
CreationClassName          : Win32_Process
CreationDate               :
CSCreationClassName        : Win32_ComputerSystem
CSName                     : SYSTEM02
Description                : System Idle Process
ExecutablePath             :
ExecutionState             :
Handle                     : 0
HandleCount                : 0
InstallDate                :
KernelModeTime             : 6138394740432
MaximumWorkingSetSize      :
MinimumWorkingSetSize      :
Name                       : System Idle Process
OSCreationClassName        : Win32_OperatingSystem
OSName                     : Microsoftr Windows VistaT Ultimate |C:\Windows|\Device\Harddisk0\Partition3
OtherOperationCount        : 0
OtherTransferCount         : 0
PageFaults                 : 0
PageFileUsage              : 0
ParentProcessId            : 0
PeakPageFileUsage          : 0
PeakVirtualSize            : 0
PeakWorkingSetSize         : 0
Priority                   : 0
PrivatePageCount           : 0
ProcessId                  : 0
QuotaNonPagedPoolUsage     : 0
QuotaPagedPoolUsage        : 0
QuotaPeakNonPagedPoolUsage : 0
QuotaPeakPagedPoolUsage    : 0
ReadOperationCount         : 0
ReadTransferCount          : 0
SessionId                  : 0
Status                     :
TerminationDate            :
ThreadCount                : 2
UserModeTime               : 0
VirtualSize                : 0
WindowsVersion             : 6.0.6001
WorkingSetSize             : 24576
WriteOperationCount        : 0
WriteTransferCount         : 0
ProcessName                : System Idle Process
Handles                    : 0
VM                         : 0
WS                         : 24576
Path                       :

...

Description
-----------
This command displays information about the services on the remote computer. It displays the information by specifying the Internet Protocol (IP) address 127.0.0.1. You can change this IP address to any other valid IP address on your network so that you can display information about the services on that remote computer. By default, the account you are running under must be a member of the local administrators group on the remote computer that you specify .

Example 3

C:\PS>get-wmiobject -namespace "root/default" -list

NameSpace: ROOT\default

Name                                Methods              Properties
----                                -------              ----------
__NotifyStatus                      {}                   {StatusCode}
__ExtendedStatus                    {}                   {Description, Operation, ParameterInfo, ProviderName...}
__SecurityRelatedClass              {}                   {}
__Trustee                           {}                   {Domain, Name, SID, SidLength...}
__NTLMUser9X                        {}                   {Authority, Flags, Mask, Name...}
__ACE                               {}                   {AccessMask, AceFlags, AceType, GuidInheritedObjectType...}
__SecurityDescriptor                {}                   {ControlFlags, DACL, Group, Owner...}
__PARAMETERS                        {}                   {}
__SystemClass                       {}                   {}
__ProviderRegistration              {}                   {provider}
__EventProviderRegistration         {}                   {EventQueryList, provider}
__ObjectProviderRegistration        {}                   {InteractionType, provider, QuerySupportLevels, SupportsBat...
__ClassProviderRegistration         {}                   {CacheRefreshInterval, InteractionType, PerUserSchema, prov...
__InstanceProviderRegistration      {}                   {InteractionType, provider, QuerySupportLevels, SupportsBat...
__MethodProviderRegistration        {}                   {provider}
__PropertyProviderRegistration      {}                   {provider, SupportsGet, SupportsPut}
__EventConsumerProviderRegistration {}                   {ConsumerClassNames, provider}
__thisNAMESPACE                     {}                   {SECURITY_DESCRIPTOR}
__NAMESPACE                         {}                   {Name}
__IndicationRelated                 {}                   {}
__FilterToConsumerBinding           {}                   {Consumer, CreatorSID, DeliverSynchronously, DeliveryQoS...}
__EventConsumer                     {}                   {CreatorSID, MachineName, MaximumQueueSize}
LogFileEventConsumer                {}                   {CreatorSID, Filename, IsUnicode, MachineName...}
ActiveScriptEventConsumer           {}                   {CreatorSID, KillTimeout, MachineName, MaximumQueueSize...}
NTEventLogEventConsumer             {}                   {Category, CreatorSID, EventID, EventType...}
SMTPEventConsumer                   {}                   {BccLine, CcLine, CreatorSID, FromLine...}
CommandLineEventConsumer            {}                   {CommandLineTemplate, CreateNewConsole, CreateNewProcessGro...
__AggregateEvent                    {}                   {NumberOfEvents, Representative}
__TimerNextFiring                   {}                   {NextEvent64BitTime, TimerId}
__EventFilter                       {}                   {CreatorSID, EventAccess, EventNamespace, Name...}
__Event                             {}                   {SECURITY_DESCRIPTOR, TIME_CREATED}
__NamespaceOperationEvent           {}                   {SECURITY_DESCRIPTOR, TargetNamespace, TIME_CREATED}
__NamespaceModificationEvent        {}                   {PreviousNamespace, SECURITY_DESCRIPTOR, TargetNamespace, T...
__NamespaceDeletionEvent            {}                   {SECURITY_DESCRIPTOR, TargetNamespace, TIME_CREATED}
__NamespaceCreationEvent            {}                   {SECURITY_DESCRIPTOR, TargetNamespace, TIME_CREATED}
__ClassOperationEvent               {}                   {SECURITY_DESCRIPTOR, TargetClass, TIME_CREATED}
__ClassDeletionEvent                {}                   {SECURITY_DESCRIPTOR, TargetClass, TIME_CREATED}
__ClassModificationEvent            {}                   {PreviousClass, SECURITY_DESCRIPTOR, TargetClass, TIME_CREA...
__ClassCreationEvent                {}                   {SECURITY_DESCRIPTOR, TargetClass, TIME_CREATED}
__InstanceOperationEvent            {}                   {SECURITY_DESCRIPTOR, TargetInstance, TIME_CREATED}
__InstanceCreationEvent             {}                   {SECURITY_DESCRIPTOR, TargetInstance, TIME_CREATED}

...

Description
-----------
This command displays the WMI classes in the root or default namespace of the local computer.

Example 4

C:\PS>get-wmiobject -query "select * from win32_service where name='WinRM'" -computername server01, server02

ExitCode  : 0
Name      : WinRM
ProcessId : 1708
StartMode : Auto
State     : Running
Status    : OK

ExitCode  : 0
Name      : WinRM
ProcessId : 948
StartMode : Auto
State     : Running
Status    : OK

Description
-----------
This command displays information about the WinRM service on the computers that are specified in the ComputerName parameter.

Example 5

C:\PS>(get-wmiobject win32_service -filter "name='WinRM'" -computername server01).StopService()

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0

Another query using get-wmiobject -query "select * from win32_service where name='WinRM'" -computername server01, shows the service as stopped.

ExitCode  : 0
Name      : WinRM
ProcessId : 0
StartMode : Auto
State     : Stopped
Status    : OK

Description
-----------
This command stops the WinRM service on the Server01 remote computer. The command uses the standard Get-WmiObject command and adds a call to the StopService method of the Win32_Service WMI class.

Example 6

C:\PS>get-wmiobject win32_bios | format-list *

Status                : OK
Name                  : Phoenix ROM BIOS PLUS Version 1.10 2.3.1
Caption               : Phoenix ROM BIOS PLUS Version 1.10 2.3.1
SMBIOSPresent         : True
__GENUS               : 2
__CLASS               : Win32_BIOS
__SUPERCLASS          : CIM_BIOSElement
__DYNASTY             : CIM_ManagedSystemElement
__RELPATH             : Win32_BIOS.Name="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",SoftwareElementID="Phoenix ROM BIOS
                         PLUS Version 1.10 2.3.1 ",SoftwareElementState=3,TargetOperatingSystem=0,Version="DELL   - 14"
__PROPERTY_COUNT      : 27
__DERIVATION          : {CIM_BIOSElement, CIM_SoftwareElement, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER              : SERVER01
__NAMESPACE           : root\cimv2
__PATH                : \\SERVER01\root\cimv2:Win32_BIOS.Name="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",Software
                        ElementID="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",SoftwareElementState=3,TargetOperatingSys
                        tem=0,Version="DELL   - 14"
BiosCharacteristics   : {7, 9, 10, 11...}
BIOSVersion           : {DELL   - 14, Phoenix ROM BIOS PLUS Version 1.10 2.3.1 , Phoenix ROM BIOS PLUS Version 1.10 2.3
                        .1 , Phoenix ROM BIOS PLUS Version 1.10 2.3.1 }
BuildNumber           :
CodeSet               :
CurrentLanguage       : en|US|iso8859-1
Description           : Phoenix ROM BIOS PLUS Version 1.10 2.3.1
IdentificationCode    :
InstallableLanguages  : 1
InstallDate           :
LanguageEdition       :
ListOfLanguages       : {en|US|iso8859-1}
Manufacturer          : Dell Inc.
OtherTargetOS         :
PrimaryBIOS           : True
ReleaseDate           : 20070521000000.000000+000
SerialNumber          : 8PWRVD1
SMBIOSBIOSVersion     : 2.3.1
SMBIOSMajorVersion    : 2
SMBIOSMinorVersion    : 3
SoftwareElementID     : Phoenix ROM BIOS PLUS Version 1.10 2.3.1
SoftwareElementState  : 3
TargetOperatingSystem : 0
Version               : DELL   - 14
Scope                 : System.Management.ManagementScope
Path                  : \\SERVER01\root\cimv2:Win32_BIOS.Name="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",Software
                        ElementID="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",SoftwareElementState=3,TargetOperatingSys
                        tem=0,Version="DELL   - 14"
Options               : System.Management.ObjectGetOptions
ClassPath             : \\SERVER01\root\cimv2:Win32_BIOS
Properties            : {BiosCharacteristics, BIOSVersion, BuildNumber, Caption...}
SystemProperties      : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers            : {dynamic, Locale, provider, UUID}
Site                  :
Container             :

Description
-----------
This command displays BIOS information. It displays all the properties of the WMI class, not just the properties that are specified in the Types.ps1xml configuration file.

Example 7

C:\PS>get-wmiobject win32_service -credential FABRIKAM\administrator -computer fabrikam

ExitCode  : 0
Name      : AeLookupSvc
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

ExitCode  : 1077
Name      : ALG
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

ExitCode  : 1077
Name      : AppIDSvc
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

ExitCode  : 0
Name      : Appinfo
ProcessId : 888
StartMode : Manual
State     : Running
Status    : OK

ExitCode  : 1077
Name      : AppMgmt
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

...

Description
-----------
This command displays service information on a computer named Fabrikam. It specifies a user account name by using the Credential parameter, which causes a dialog box to be displayed in which you enter the corresponding password.

See Also

  • Invoke-WmiMethod
  • Remove-WmiObject
  • Set-WmiInstance
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • Remove-WSManInstance


Get-WSManCredSSP

Gets the Credential Security Service Provider-related configuration for the client.

Syntax

Get-WSManCredSSP [<CommonParameters>]

Description

The Get-WSManCredSPP cmdlet gets the Credential Security Service Provider-related configuration of the client and the server. The output indicates whether Credential Security Service Provider (CredSSP) authentication is enabled or disabled. It also displays configuration information for the AllowFreshCredentials policy of CredSSP. When you use CredSSP authentication, the user's credentials are passed to a remote computer to be authenticated. This type of authentication is designed for commands that create a remote session from within another remote session. For example, you use this type of authentication if you want to run a background job on a remote computer.

The cmdlet performs the following actions:

- Gets the WS-Management CredSSP setting on the client (<localhost|computername>\Client\Auth\CredSSP).

- Gets the Windows CredSSP policy setting AllowFreshCredentials.

- Gets the WS-Management CredSSP setting on the server (<localhost|computername>\Service\Auth\CredSSP).

Caution: CredSSP authentication delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

To disable CredSSP authentication, use the Disable-WSManCredSSP cmdlet. To enable CredSSP authentication, use the Enable-WSManCredSSP cmdlet.

Parameters

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>get-wsmancredssp

This command displays CredSSP configuration information for both the client and server.

The output identifies that this computer is or is not configured for CredSSP.

If the computer is configured for CredSSP, this is the output:

"The machine is configured to allow delegating fresh credentials to the following target(s): wsman/server02.accounting.fabrikam.com"

If the computer is not configured for CredSSP, this is the output:

"The machine is not configured to allow delegating fresh credentials."

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


Get-WSManInstance

Displays management information for a resource instance specified by a Resource URI.

Syntax

Get-WSManInstance -SelectorSet <hashtable> [-ApplicationName <string>] [-ComputerName <string>] [-Credential <PSCredential>] [-Fragment <string>] [-Port <int>] [-UseSSL] [-ResourceURI] <Uri> [-Authentication <Authentication>] [-Dialect <Uri>] [-OptionSet <hashtable>] [-SessionOption <hashtable>] [<CommonParameters>]

Get-WSManInstance [-ApplicationName <string>] [-BasePropertiesOnly <switch>] [-ComputerName <string>] [-Credential <PSCredential>] [-Enumerate] [-filter <string>] [-Port <int>] [-References <switch>] [-ReturnType <string>] [-Shallow <switch>] [-UseSSL] [-ResourceURI] <Uri> [-Authentication <Authentication>] [-Dialect <Uri>] [-OptionSet <hashtable>] [-SessionOption <hashtable>] [<CommonParameters>]

Get-WSManInstance -ConnectionURI <Uri> -SelectorSet <hashtable> [-Fragment <string>] [-ResourceURI] <Uri> [-Authentication <Authentication>] [-Dialect <Uri>] [-OptionSet <hashtable>] [-SessionOption <hashtable>] [<CommonParameters>]

Get-WSManInstance -ConnectionURI <Uri> [-BasePropertiesOnly <switch>] [-Enumerate] [-filter <string>] [-References <switch>] [-ReturnType <string>] [-Shallow <switch>] [-ResourceURI] <Uri> [-Authentication <Authentication>] [-Dialect <Uri>] [-OptionSet <hashtable>] [-SessionOption <hashtable>] [<CommonParameters>]

Description

The Get-WSManInstance cmdlet retrieves an instance of a management resource that is specified by a resource URI. The information that is retrieved can be a complex XML information set (an object) or a simple value. This cmdlet is the equivalent to the standard WS-Management Get command.

This cmdlet uses the WS-Management connection/transport layer to retrieve information.

Parameters

-ApplicationName <string>

Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for the remote endpoint is in the following format:

<transport>://<server>:<port>/<ApplicationName>

For example:

http://server01:8080/WSMAN

Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency.

Required? | false
Position? | named
Default Value | wsman
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <Authentication>

Specifies the authentication mechanism to be used at the server. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.

- Default : Use the authentication method implemented by the WS-Management protocol. This is the default.

- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

- Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates.

- Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.

- CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

Caution: CredSSP delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

Required? | false
Position? | named
Default Value | Default
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-BasePropertiesOnly <switch>

Enumerates only the properties that are part of the base class that is specified by the ResourceURI parameter. This parameter has no effect if the Shallow parameter is specified.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

Required? | false
Position? | named
Default Value | localhost
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ConnectionURI <Uri>

Specifies the connection endpoint. The format of this string is:

<Transport>://<Server>:<Port>/<ApplicationName>

The following string is a properly formatted value for this parameter:

http://Server01:8080/WSMAN

The URI must be fully qualified.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Domain.com". Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Dialect <Uri>

Specifies the dialect to use in the filter predicate. This can be any dialect that is supported by the remote service. The following aliases can be used for the dialect URI:

- WQL: http://schemas.microsoft.com/wbem/wsman/1/WQL

- Selector: http://schemas.microsoft.com/wbem/wsman/1/wsman/SelectorFilter

- Association: http://schemas.dmtf.org/wbem/wsman/1/cimbinding/associationFilter

Required? | false
Position? | named
Default Value | http://schemas.microsoft.com/wbem/wsman/1/WQL
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Enumerate

Returns all of the instances of a management resource.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-filter <string>

Specifies the filter expression for the enumeration. If you use this parameter, you must also specify the Dialect parameter.

The valid values of this parameter depend on the dialect that is specified in the Dialect parameter. For example, if the Dialect parameter is set to WQL, the Filter parameter must contain a string, and the string must contain a valid WQL query such as the following query:

"Select * from Win32_Service where State != Running"

If the Dialect parameter is set to Association, the Filter parameter must contain a string, and the string must contain a valid filter, such as the following filter:

-filter:Object=EPR[;AssociationClassName=AssocClassName][;ResultClassName=ClassName][;Role=RefPropertyName][;ResultRole=RefPropertyName]}

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Fragment <string>

Specifies a section inside the instance that is to be updated or retrieved for the specified operation. For example, to get the status of a spooler service, specify "-Fragment Status".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OptionSet <hashtable>

Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified.

The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters:

-OptionSet @{a=1;b=2;c=3}

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Port <int>

Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server's certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted computers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-References <switch>

Indicates that association instances (not associated instances) should be retrieved. You can use this parameter only when the Dialect parameter is set to a value of "Association".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ResourceURI <Uri>

Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer.

A URI consists of a prefix and a path to a resource. For example:

http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk

http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-ReturnType <string>

Specifies the type of data to be returned. The valid values are:

Object (the default)

EPR

ObjectAndEPR

If Object is specified or if this parameter is not used, only objects are returned. If EPR (endpoint reference) is specified, only the endpoint references of the objects are returned. Endpoint references contain information about the resource URI and the selectors for the instance. If ObjectAndEPR is specified, both the object and its associated endpoint references are returned.

Required? | false
Position? | named
Default Value | Object
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SelectorSet <hashtable>

Specifies a set of value pairs that are used to select particular management resource instances. The SelectorSet parameter is used when more than one instance of the resource exists. The value of the SelectorSet parameter must be a hash table.

The following example shows how to enter a value for this parameter:

-SelectorSet @{Name="WinRM";ID="yyy"}

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SessionOption <hashtable>

Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, see New-WSManSessionOption.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Shallow <switch>

Causes only instances of the base class that is specified in the resource URI to be returned. If this switch is not specified, instances of the base class that is specified in the URI and in all its derived classes is returned.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This command does not accept any input.
Outputs | System.Xml.XmlElement The Get-WSManInstance cmdlet generates an XMLElement object.

Example 1

C:\PS>get-wsmaninstance wmicimv2/win32_service -selectorset @{name="winrm"} -computername server01

xsi                     : http://www.w3.org/2001/XMLSchema-instance
p                       : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
cim                     : http://schemas.dmtf.org/wbem/wscim/1/common
type                    : p:Win32_Service_Type
lang                    : en-US
AcceptPause             : false
AcceptStop              : true
Caption                 : Windows Remote Management (WS-Management)
CheckPoint              : 0
CreationClassName       : Win32_Service
Description             : Windows Remote Management (WinRM) service implements the WS-Management protocol for remote
                          management. WS-Management is a standard web services protocol used for remote software and
                          hardware management. The WinRM service listens on the network for WS-Management requests
                          and processes them. The WinRM Service needs to be configured with a listener using the
                          winrm.cmd command line tool or through Group Policy in order for it to listen over the
                          network. The WinRM service provides access to WMI data and enables event collection. Event
                          collection and subscription to events require that the service is running. WinRM messages
                          use HTTP and HTTPS as transports. The WinRM service does not depend on IIS but is
                          preconfigured to share a port with IIS on the same machine.  The WinRM service reserves the
                          /wsman URL prefix. To prevent conflicts with IIS, administrators should ensure that any
                          websites hosted on IIS do not use the /wsman URL prefix.
DesktopInteract         : false
DisplayName             : Windows Remote Management (WS-Management)
ErrorControl            : Normal
ExitCode                : 0
InstallDate             : InstallDate
Name                    : winrm
PathName                : C:\Windows\System32\svchost.exe -k NetworkService
ProcessId               : 948
ServiceSpecificExitCode : 0
ServiceType             : Share Process
Started                 : true
StartMode               : Auto
StartName               : NT AUTHORITY\NetworkService
State                   : Running
Status                  : OK
SystemCreationClassName : Win32_ComputerSystem
SystemName              : SERVER01
TagId                   : 0
WaitHint                : 0

Description
-----------
This command returns all of the information that Windows Management Instrumentation (WMI) exposes about the WinRM service on the remote server01 computer.

Example 2

C:\PS>get-wsmaninstance wmicimv2/win32_service -selectorset @{name="spooler"} -fragment status -computername server01

XmlFragment=OK

Description
-----------
This command returns only the status of the Spooler service on the remote server01 computer.

Example 3

C:\PS>get-wsmaninstance -enumerate wmicimv2/win32_process

OSName                     : Microsoft Windows Vista Ultimate |C:\Windows|\Device\Harddisk0\Partition3
OtherOperationCount        : 11441
OtherTransferCount         : 428570
PageFaults                 : 27346
PageFileUsage              : 16428
ParentProcessId            : 604
PeakPageFileUsage          : 17588
PeakVirtualSize            : 93876224
PeakWorkingSetSize         : 12472
Priority                   : 8
PrivatePageCount           : 16822272
ProcessId                  : 1160
QuotaNonPagedPoolUsage     : 14
QuotaPagedPoolUsage        : 126
QuotaPeakNonPagedPoolUsage : 16
QuotaPeakPagedPoolUsage    : 159
ReadOperationCount         : 29568
ReadTransferCount          : 1660581404
SessionId                  : 0
Status                     : Status
TerminationDate            : TerminationDate
ThreadCount                : 23
UserModeTime               : 763156892
VirtualSize                : 80846848
WindowsVersion             : 6.0.6001
WorkingSetSize             : 11624448
WriteOperationCount        : 1913
WriteTransferCount         : 6825768

xsi                        : http://www.w3.org/2001/XMLSchema-instance
p                          : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process
cim                        : http://schemas.dmtf.org/wbem/wscim/1/common
type                       : p:Win32_Process_Type
lang                       : en-US
Caption                    : svchost.exe
CommandLine                : C:\Windows\System32\svchost.exe -k LocalSystemNetworkRestricted
CreationClassName          : Win32_Process
CreationDate               : CreationDate
CSCreationClassName        : Win32_ComputerSystem
CSName                     : COMPUTER01
Description                : svchost.exe
ExecutablePath             : C:\Windows\System32\svchost.exe
ExecutionState             : ExecutionState
Handle                     : 1192
HandleCount                : 832

...

Description
-----------
This command returns all the instances of the WMI Win32_Process class on the local computer.

Example 4

C:\PS>get-wsmaninstance -enumerate wmicimv2/win32_service -returntype epr

xsi                     : http://www.w3.org/2001/XMLSchema-instance
p                       : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
cim                     : http://schemas.dmtf.org/wbem/wscim/1/common
type                    : p:Win32_Service_Type
lang                    : en-US
AcceptPause             : false
AcceptStop              : false
Caption                 : Visual Studio 2008 Remote Debugger
CheckPoint              : 0
CreationClassName       : Win32_Service
Description             : Allows members of the Administrators group to remotely debug server applications using Visual
                           Studio 2008. Use the Visual Studio 2008 Remote Debugging Configuration Wizard to enable this
                           service.
DesktopInteract         : false
DisplayName             : Visual Studio 2008 Remote Debugger
ErrorControl            : Ignore
ExitCode                : 1077
InstallDate             : InstallDate
Name                    : msvsmon90
PathName                : "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger\x86\msvsmon.exe" /s
                          ervice msvsmon90
ProcessId               : 0
ServiceSpecificExitCode : 0
ServiceType             : Own Process
Started                 : false
StartMode               : Disabled
StartName               : LocalSystem
State                   : Stopped
Status                  : OK
SystemCreationClassName : Win32_ComputerSystem
SystemName              : COMPUTER01
TagId                   : 0
WaitHint                : 0

...

Description
-----------
This command returns endpoint references that correspond to all the services on the local computer.

Example 5

C:\PS>Get-WSManInstance -Enumerate wmicimv2/* -filter "select * from win32_service where StartMode = 'Auto' and State = 'Stopped'" -computername server01

xsi                     : http://www.w3.org/2001/XMLSchema-instance
p                       : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
cim                     : http://schemas.dmtf.org/wbem/wscim/1/common
type                    : p:Win32_Service_Type
lang                    : en-US
AcceptPause             : false
AcceptStop              : false
Caption                 : Windows Media Center Service Launcher
CheckPoint              : 0
CreationClassName       : Win32_Service
Description             : Starts Windows Media Center Scheduler and Windows Media Center Receiver services
                          at startup if TV is enabled within Windows Media Center.
DesktopInteract         : false
DisplayName             : Windows Media Center Service Launcher
ErrorControl            : Ignore
ExitCode                : 0
InstallDate             : InstallDate
Name                    : ehstart
PathName                : C:\Windows\system32\svchost.exe -k LocalServiceNoNetwork
ProcessId               : 0
ServiceSpecificExitCode : 0
ServiceType             : Share Process
Started                 : false
StartMode               : Auto
StartName               : NT AUTHORITY\LocalService
State                   : Stopped
Status                  : OK
SystemCreationClassName : Win32_ComputerSystem
SystemName              : Server01
TagId                   : 0
WaitHint                : 0

...

Description
-----------
This command lists all of the services that meet the following criteria on the remote server01 computer:

   - The startup type of the service is "Automatic".
   - The service is stopped.

Example 6

C:\PS>get-wsmaninstance winrm/config/listener -selectorset @{Address="*";Transport="http"}

cfg                   : http://schemas.microsoft.com/wbem/wsman/1/config/listener
xsi                   : http://www.w3.org/2001/XMLSchema-instance
lang                  : en-US
Address               : *
Transport             : HTTP
Port                  : 80
Hostname              :
Enabled               : true
URLPrefix             : wsman
CertificateThumbprint :
ListeningOn           : {100.0.0.1, 123.123.123.123, ::1, 2001:4898:0:fff:0:5efe:123.123.123.123...}

Description
-----------
This command lists the WS-Management listener configuration on the local computer for the listener that matches the criteria in the selector set.

Example 7

C:\PS>get-wsmaninstance winrm/config/listener -selectorset @{Address="*";Transport="http"} -computername server01

cfg                   : http://schemas.microsoft.com/wbem/wsman/1/config/listener
xsi                   : http://www.w3.org/2001/XMLSchema-instance
lang                  : en-US
Address               : *
Transport             : HTTP
Port                  : 80
Hostname              :
Enabled               : true
URLPrefix             : wsman
CertificateThumbprint :
ListeningOn           : {100.0.0.1, 123.123.123.124, ::1, 2001:4898:0:fff:0:5efe:123.123.123.124...}

Description
-----------
This command lists the WS-Management listener configuration on the remote server01 computer for the listener that matches the criteria in the selector set.

Example 8

C:\PS>Get-WSManInstance -Enumerate -Dialect association -filter "{Object=win32_service?name=winrm}" -res wmicimv2/*

xsi                       : http://www.w3.org/2001/XMLSchema-instance
p                         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_ComputerSystem
cim                       : http://schemas.dmtf.org/wbem/wscim/1/common
type                      : p:Win32_ComputerSystem_Type
lang                      : en-US
AdminPasswordStatus       : 1
AutomaticManagedPagefile  : true
AutomaticResetBootOption  : true
AutomaticResetCapability  : true
BootOptionOnLimit         : BootOptionOnLimit
BootOptionOnWatchDog      : BootOptionOnWatchDog
BootROMSupported          : true
BootupState               : Normal boot
Caption                   : SERVER01
ChassisBootupState        : 3
CreationClassName         : Win32_ComputerSystem
CurrentTimeZone           : -480
DaylightInEffect          : false
Description               : AT/AT COMPATIBLE
DNSHostName               : server01
Domain                    : site01.corp.fabrikam.com
DomainRole                : 1
EnableDaylightSavingsTime : true
FrontPanelResetStatus     : 2
InfraredSupported         : false
InstallDate               : InstallDate
KeyboardPasswordStatus    : 2
LastLoadInfo              : LastLoadInfo
Manufacturer              : Dell Inc.
Model                     : OptiPlex 745
Name                      : SERVER01
NameFormat                : NameFormat
NetworkServerModeEnabled  : true
NumberOfLogicalProcessors : 2
NumberOfProcessors        : 1
OEMStringArray            : www.dell.com
PartOfDomain              : true
PauseAfterReset           : -1
PCSystemType              : 5
PowerManagementSupported  : PowerManagementSupported
PowerOnPasswordStatus     : 1
PowerState                : 0
PowerSupplyState          : 3
PrimaryOwnerContact       : PrimaryOwnerContact
PrimaryOwnerName          : testuser01
ResetCapability           : 1
ResetCount                : -1
ResetLimit                : -1
Roles                     : {LM_Workstation, LM_Server, SQLServer, NT}
Status                    : OK
SystemStartupDelay        : SystemStartupDelay
SystemStartupSetting      : SystemStartupSetting
SystemType                : X86-based PC
ThermalState              : 3
TotalPhysicalMemory       : 3217760256
UserName                  : FABRIKAM\testuser01
WakeUpType                : 6
Workgroup                 : Workgroup

xsi                     : http://www.w3.org/2001/XMLSchema-instance
p                       : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
cim                     : http://schemas.dmtf.org/wbem/wscim/1/common
type                    : p:Win32_Service_Type
lang                    : en-US
AcceptPause             : false
AcceptStop              : false
Caption                 : Remote Procedure Call (RPC)
CheckPoint              : 0
CreationClassName       : Win32_Service
Description             : Serves as the endpoint mapper and COM Service Control Manager. If this service is stopped
                          or disabled, programs using COM or Remote Procedure Call (RPC) services will not function
                          properly.
DesktopInteract         : false
DisplayName             : Remote Procedure Call (RPC)
ErrorControl            : Normal
ExitCode                : 0
InstallDate             : InstallDate
Name                    : RpcSs
PathName                : C:\Windows\system32\svchost.exe -k rpcss
ProcessId               : 1100
ServiceSpecificExitCode : 0
ServiceType             : Share Process
Started                 : true
StartMode               : Auto
StartName               : NT AUTHORITY\NetworkService
State                   : Running
Status                  : OK
SystemCreationClassName : Win32_ComputerSystem
SystemName              : SERVER01
TagId                   : 0
WaitHint                : 0

xsi                     : http://www.w3.org/2001/XMLSchema-instance
p                       : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_SystemDriver
cim                     : http://schemas.dmtf.org/wbem/wscim/1/common
type                    : p:Win32_SystemDriver_Type
lang                    : en-US
AcceptPause             : false
AcceptStop              : true
Caption                 : HTTP
CreationClassName       : Win32_SystemDriver
Description             : HTTP
DesktopInteract         : false
DisplayName             : HTTP
ErrorControl            : Normal
ExitCode                : 0
InstallDate             : InstallDate
Name                    : HTTP
PathName                : C:\Windows\system32\drivers\HTTP.sys
ServiceSpecificExitCode : 0
ServiceType             : Kernel Driver
Started                 : true
StartMode               : Manual
StartName               :
State                   : Running
Status                  : OK
SystemCreationClassName : Win32_ComputerSystem
SystemName              : SERVER01
TagId                   : 0

Description
-----------
This command gets the associated instances that are related to the specified instance (winrm).

Important: You must enclose the filter in quotation marks, as shown in the example.

Example 9

C:\PS>Get-WSManInstance -Enumerate -Dialect association -References -filter "{Object=win32_service?name=winrm}" -res wmicimv2/*

This command gets association instances that are related to the specified instance (winrm). Because the Dialect parameter is set to "association" and the Reference parameter is used, this command returns  association instances,  not associated instances.

Important: You must enclose the filter in quotation marks, as shown in the example.

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


Group-Object

Groups objects that contain the same value for specified properties.

Syntax

Group-Object [-AsHashTable] [-AsString] [[-Property] <Object[]>] [-CaseSensitive] [-Culture <string>] [-InputObject <psobject>] [-NoElement] [<CommonParameters>]

Description

The Group-Object cmdlet displays objects in groups based on the value of a specified property. Group-Object returns a table with one row for each property value and a column that displays the number of items with that value.

If you specify more than one property, Group-Object first groups them by the values of the first property, and then, within each property group, it groups by the value of the next property.

Parameters

-AsHashTable

Returns the group as a hash table. The keys of the hash table are the property values by which the objects are grouped. The values of the hash table are the objects that have that property value.

By itself, the AsHashTable parameter returns each hash table in which each key is an instance of the grouped object. When used with the AsString parameter, the keys in the hash table are strings.

Required? | false
Position? | named
Default Value | GroupInfo object
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsString

Converts the hash table keys to strings. By default, the hash table keys are instances of the grouped object. This parameter is valid only when used with the AsHashTable parameter.

Required? | false
Position? | named
Default Value | GroupInfo objects
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CaseSensitive

Makes the grouping case-sensitive. Without this parameter, the property values of objects in a group might have different cases.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Culture <string>

Specifies the culture to use when comparing strings.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to group. Enter a variable that contains the objects, or type a command or expression that gets the objects.

When you use the InputObject parameter to submit a collection of objects to Group-Object, Group-Object receives one object that represents the collection. As a result, it creates a single group with that object as its member.

To group the objects in a collection, pipe the objects to Group-Object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-NoElement

Omits the members of a group from the results.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Property <Object[]>

Specifies the properties for grouping. The objects are arranged into groups based on the value of the specified property.

The value of the Property parameter can be a new calculated property. To create a calculated, property, create a hash table with an Expression key that specifies a string or script block value.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Group-Object
Outputs | Microsoft.PowerShell.Commands.GroupInfo or System.Collections.Hashtable When you use the AsHashTable parameter, Group-Object returns a hash table. Otherwise, it returns a GroupInfo object.

Notes

You can also use the GroupBy parameter of the formatting cmdlets (such as Format-Table [m2] and Format-List [m2]) to group objects. Unlike Group-Object, which creates a single table with a row for each property value, the GroupBy parameters create a table for each property value with a row for each item that has the property value.

Group-Object does not require that the objects being grouped be of the same Microsoft .NET Framework type. When grouping objects of different .NET Framework types, Group-Object uses the following rules:

-- Same Property Names and Types: If the objects have a property with the specified name, and the property values have the same .NET Framework type, the property values are grouped by using the same rules that would be used for objects of the same type.

-- Same Property Names, Different Types: If the objects have a property with the specified name, but the property values have a different .NET Framework type in different objects, Group-Object uses the .NET Framework type of the first occurrence of the property as the .NET Framework type for that property group. When an object has a property with a different type, the property value is converted to the type for that group. If the type conversion fails, the object is not included in the group.

-- Missing Properties: Objects that do not have a specified property are considered ungroupable. Ungroupable objects appear in the final GroupInfo object output in a group named AutomationNull.Value.

Example 1

C:\PS>get-childitem *.doc | group-object -property length

This command gets the files in the current location that have a .doc extension and groups them by size.

Example 2

C:\PS>get-childitem | sort-object -property extension | group-object -property extension

This command gets the files in the current location, sorts them by file name extension, and then groups them by file name extension. Note that the files are sorted before they are grouped.

Example 3

C:\PS>1..35 | group-object -property {$_ % 2},{$_ % 3}

This example shows how to use script blocks as the value of the Property parameter.

This command displays the integers from 1 to 35, grouped by the remainder left when they are divided by 2 or 3.

Example 4

C:\PS>$events = get-eventlog -logname system -newest 1000

C:\PS> $events | group-object -property eventID

Count Name                      Group
----- ----                      -----
   44 Information               {System.Diagnostics.EventLogEntry,
    5 Error                     {System.Diagnostics.EventLogEntry,
    1 Warning                   {System.Diagnostics.EventLogEntry}

Description
-----------
These commands display the 1,000 most recent entries in the System event log, grouped by Event ID.

The first command uses the Get-EventLog cmdlet to retrieve the events and the assignment operator (=) to save them in the $events variable.

The second command uses a pipeline operator (|) to send the events in the $events variable to the Group-Object cmdlet. The command uses the Property parameter to specify that the events should be grouped according to the value of their EventID property.

In the output, the Count column represents the number of entries in each group, the Name column represents the EventID values that define a group, and the Group column represents the objects in each group.

Example 5

C:\PS>get-process | group-object -property priorityclass

Count Name                Group
----- ----                -----
   55 Normal              {System.Diagnostics.Process (AdtAgent), System.Diagnostics.Process (alg), System.Dia...
    1                     {System.Diagnostics.Process (Idle)}
    3 High                {System.Diagnostics.Process (Newproc), System.Diagnostics.Process (winlogon), System.D...
    2 BelowNormal         {System.Diagnostics.Process (winperf),

C:\PS>get-process | group-object -property company -noelement
Count Name
----- ----
   55 Normal
    1
    3 High
    2 BelowNormal

Description
-----------
This example demonstrates the effect of the NoElement parameter. These commands group the processes on the computer by priority class.

The first command uses the Get-Process cmdlet to get the processes on the computer. It uses a pipeline operator (|) to send the results to Group-Object, which groups the objects by the value of the PriorityClass property of the process.

The second command is identical to the first, except that it uses the NoElement parameter to eliminate the members of the group from the output. The result is a table with only the count and property value name.

The results are shown in the following sample output.

Example 6

C:\PS>get-eventlog -logname system -newest 1000 | group-object -property {$_.TimeWritten - $_.TimeGenerated}

This command demonstrates how to provide the value of the Property parameter as a script block.

This command displays the most recent 1,000 entries from the system event log, grouped according to the time between when they were generated and when they were written to the log.

The command uses the Get-EventLog cmdlet to get the event log entries. It uses a pipeline operator (|) to send the entries to the Group-Object cmdlet. The value of the Property parameter is specified as a script block (an expression in braces). The result of evaluating the script block is the time between when the log entry was generated and when it was written to the log. That value is used to group the 1,000 most recent events.

Example 7

C:\PS>get-childitem | group-object extension -noelement

Count Name
----- ----
   21
   82 .txt
    9 .cmd
    5 .log
   12 .xml
    5 .htm
   36 .ps1
    1 .psc1
    3 .exe
    6 .csv
    1 .psd1
    2 .bat

Description
-----------
This command groups the items in the current directory by file name extension. It uses the NoElement parameter to omit the members of the group.

The results are shown in the following sample output.

Example 8

C:\PS>"a", "b", "c", "c", "d" | get-unique

a
b
c
d

C:\PS> "a", "b", "c", "c", "d" | group-object -noelement | where {$_.Count -gt 1}
Count Name
----- ----
    2 c

C:\PS> get-process | group-object -property Name -noelement | where {$_.count -gt 1}
Count Name
----- ----
    2 csrss
    5 svchost
    2 winlogon
    2 wmiprvse

Description
-----------
This example shows how to find the unique and non-unique (repeated) property values in a collection.

The first command gets the unique elements of an array by piping the array to the Get-Unique cmdlet.

The second command gets the non-unique elements of an array. It pipes the array to the Group-Object cmdlet, which groups the objects by value. The resulting groups are piped to the Where-Object cmdlet, which selects objects with groups with more than one member.

The third command shows a practical use for this technique. It uses the same method to find processes on the computer that have the same process name.

The results are shown in the following sample output.

Example 9

C:\PS>$a = get-command get-*, set-* -type cmdlet | group-object -property verb -ashashtable -asstring

C:\PS> $a

Name    Value
----    -----
Get     {Get-PSCallStack, Get-PSBreakpoint, Get-PSDrive, Get-PSSession...}
Set     {Set-Service, Set-StrictMode, Set-PSDebug, Set-PSSessionConfiguration...}

C:\PS> $a.get

CommandType     Name                 Definition
-----------     ----                 ----------
Cmdlet          Get-PSCallStack      Get-PSCallStack [-Verbose] [-Debug] [-ErrorAction <ActionPrefer...
Cmdlet          Get-PSBreakpoint     Get-PSBreakpoint [[-Id] <Int32[]>] [-Verbose] [-Debug] [-ErrorA...
Cmdlet          Get-PSDrive          Get-PSDrive [[-Name] <String[]>] [-Scope <String>] [-PSProvider...
...

Description
-----------
This example uses the AsHashTable and AsString parameters to return the groups in a hash table, that is, as a collection of key-value pairs.

In the resulting hash table, each property value is a key, and the group elements are the values. Because each key is a property of the hash table object, you can use dot notation to display the values.

The first command gets the Get and Set cmdlets in the session, groups them by verb, returns the groups as a hash table, and saves the hash table in the $a variable.

The second command displays the hash table in $a. There are two key-value pairs, one for the Get cmdlets and one for the Set cmdlets.

The third command uses dot notation to display the values of the Get key in $a. The values are CmdletInfo object. The AsString parameter does not convert the objects in the groups to strings.


Import-Alias

Imports an alias list from a file.

Syntax

Import-Alias [-Path] <string> [-Force] [-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Import-Alias cmdlet imports an alias list from a file.

Parameters

-Force

Allows the cmdlet to import an alias that is already defined and is read only. You can use the following command to display information about the currently-defined aliases:

get-alias | Select-Object name,Options

The value of the Options property will include "ReadOnly" if the corresponding alias is read only.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the alias. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the path to a file that includes exported alias information. Wildcards are allowed but they must resolve to a single name.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Scope <string>

Specifies the scope into which the aliases are imported. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Import-Alias.
Outputs | None or System.Management.Automation.AliasInfo When you use the Passthru parameter, Import-Alias returns a System.Management.Automation.AliasInfo object that represents the alias. Otherwise, this cmdlet does not generate any output.

Example 1

C:\PS>import-alias test.txt

This command imports alias information from a file named test.txt.

See Also

  • Export-Alias
  • Get-Alias
  • New-Alias
  • Set-Alias


Import-Clixml

Imports a CLIXML file and creates corresponding objects within Windows PowerShell.

Syntax

Import-Clixml [-Path] <string[]> [<CommonParameters>]

Description

The Import-Clixml cmdlet imports a CLIXML file with data that represents Microsoft .NET Framework objects and creates the objects in Windows PowerShell.

Parameters

-Path <string[]>

Specifies the location of the XML files to be converted into Windows PowerShell objects.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Import-Clixml.
Outputs | PSObjects Import-Clixml returns objects that have been deserialized from the stored XML files.

Notes

When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>".

Example 1

C:\PS>get-process | export-clixml pi.xml

C:\PS> $processes = import-clixml pi.xml

This command uses the Export-Clixml cmdlet to save a serialized copy of the process information returned by Get-Process. It then uses Import-Clixml to retrieve the contents of the serialized file and re-create an object that is stored in the $processes variable.


Import-Counter

Imports performance counter log files (.blg, .csv, .tsv) and creates the objects that represent each counter sample in the log.

Syntax

Import-Counter [-Path] <string[]> [-Counter <string[]>] [-EndTime <DateTime>] [-MaxSamples <Int64>] [-StartTime <DateTime>] [<CommonParameters>]

Import-Counter [-Path] <string[]> -ListSet <string[]> [<CommonParameters>]

Import-Counter [-Path] <string[]> -Summary <switch> [<CommonParameters>]

Description

The Import-Counter cmdlet imports performance counter data from performance counter log files and creates objects for each counter sample in the file. The PerformanceCounterSampleSet objects that it creates are identical to the objects that Get-Counter returns when it collects performance counter data.

You can import data from comma-separated value (.csv), tab-separated value ( .tsv), and binary performance log (.blg) performance log files. If you are using .blg files, you can import multiple files (up to 32 different files) in each command. And, you can use the parameters of Import-Counter to filter the data that you import.

Along with Get-Counter and Export-Counter, this feature lets you collect, export, import, combine, filter, manipulate, and re-export performance counter data within Windows PowerShell.

Parameters

-Counter <string[]>

Imports data only for the specified performance counters. By default, Import-Counter imports all data from all counters in the input files. Enter one or more counter paths. Wildcards are permitted in the Instance part of the path.

Each counter path has the following format. Notice that the ComputerName value is required in the path, even on the local computer.

"\\<ComputerName>\<CounterSet>(<Instance>)\<CounterName>"

For example:

"\\Server01\Processor(2)\% User Time"

"\Processor(*)\% Processor Time

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-EndTime <DateTime>

Imports only counter data with a timestamp less than or equal to the specified date and time. Enter a DateTime object, such as one created by the Get-Date cmdlet. By default, Import-Counter imports all counter data in the files specified by the Path parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ListSet <string[]>

Gets the performance counter sets that are represented in the exported files. Commands with this parameter do not import any data.

Enter one or more counter set names. Wildcards are permitted. To get all counter sets in the file, type "import-counter -listset *".

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-MaxSamples <Int64>

Specifies the maximum number of samples of each counter to import. By default, Get-Counter imports all of the data in the files specified by the Path parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the file paths of the files to be imported. This parameter is required.

Enter the path and file name of a, .csv,, .tsv, or .blg file that you exported by using the Export-Counter cmdlet. You can specify only one .csv or .tsv file, but you can specify multiple .blg files (up to 32) in each command. You can also pipe file path strings (in quotation marks) to Import-Counter.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | true

-StartTime <DateTime>

Imports only counter data with a timestamp greater than or equal to the specified date and time. Enter a DateTime object, such as one created by the Get-Date cmdlet. By default, Import-Counter imports all counter data in the files specified by the Path parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Summary <switch>

Gets a summary of the imported data, instead of getting individual counter data samples.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs

System.String

You can pipe performance counter log paths to Import-Counter.

Outputs

Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet, Microsoft.PowerShell.Commands.GetCounter.CounterSet, Microsoft.PowerShell.Commands.GetCounter.CounterFileInfo

By default, Import-Counter returns a Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet. If you use the ListSet parameter, Import-Command returns a Microsoft.PowerShell.Commands.GetCounter.CounterSet object. If you use the Summary parameter, Import-Command returns a Microsoft.PowerShell.Commands.GetCounter.CounterFileInfo object.

Notes

The Import-Counter cmdlet does not have a ComputerName parameter. However, if the computer is configured for Windows PowerShell remoting, you can use the Invoke-Command cmdlet to run an Import-Counter command on a remote computer.

Example 1

C:\PS>$data = import-counter -path ProcessorData.csv

This command imports all of the counter data from the ProcessorData.csv file into the $data variable.

Example 2

C:\PS>$i = import-counter -path ProcessorData.blg -counter "\\SERVER01\Processor(_Total)\Interrupts/sec"

This command imports only the Processor(_total)\Interrupts\sec counter data from the ProcessorData.blg file into the $i variable.

Example 3

C:\PS>$data = import-counter .\processordata.blg

C:\PS> $data[0].countersamples | format-table path

Path
----
\\SERVER01\Processor(_Total)\DPC Rate
\\SERVER01\Processor(1)\DPC Rate
\\SERVER01\Processor(0)\DPC Rate
\\SERVER01\Processor(_Total)\% Idle Time
\\SERVER01\Processor(1)\% Idle Time
\\SERVER01\Processor(0)\% Idle Time
\\SERVER01\Processor(_Total)\% C3 Time
\\SERVER01\Processor(1)\% C3 Time
...

C:\PS> $IntCtrs = $data[0].countersamples | where {$_.path -like "*interrupts/sec"} | foreach {$_.path}

C:\PS> $IntCtrs

\\SERVER01\Processor(_Total)\Interrupts/sec
\\SERVER01\Processor(1)\Interrupts/sec
\\SERVER01\Processor(0)\Interrupts/sec

C:\PS> $i = import-counter -path .\processordata.blg -counter $intCtrs

C:\PS> $i | export-counter -path .\interrupts.csv -format CSV

Description
-----------
This example shows how to select data from a performance counter log file (.blg) and then export the selected data to a .csv file.

The first four commands get the counter paths from the file and save them in a variable. The last two commands import selected data and then export only the selected data.

The first command uses Import-Counter to import all of the performance counter data from the ProcessorData.blg files. The command saves the data in the $data variable.

The second command displays the counter paths in the $data variable. The display is shown in the command output.

The third command gets the counter paths that end in "Interrupts/sec" and saves the paths in the $IntCtrs variable.

The fourth command displays the selected counter paths.

The fifth command uses the Import-Counter cmdlet to import the data. It uses the Counter parameter with the $IntCtrs variable to import only data for the counter paths in $IntCtrs.

The sixth command uses the Export-Counter cmdlet to export the data.

Example 4

C:\PS>import-counter -path processordata.csv -listset *

CounterSetName     : Processor
MachineName        : \\SERVER01
CounterSetType     : MultiInstance
Description        : The Processor performance object consists of counters that measure aspects of processor activity T
                     he processor is the part of the computer that performs arithmetic and logical computations, initia
                     tes operations on peripherals, and runs the threads of processes.  A computer can have multiple pr
                     ocessors.  The processor object represents each processor as an instance of the object.
Paths              : {\\SERVER01\Processor(*)\DPC Rate, \\SERVER01\Processor(*)\% Idle Time, \\SERVER01\Processor
                     (*)\% C3 Time, \\SERVER01\Processor(*)\% Interrupt Time...}
PathsWithInstances : {\\SERVER01\Processor(_Total)\DPC Rate, \\SERVER01\Processor(1)\DPC Rate, \\SERVER01\Process
                     or(0)\DPC Rate, \\SERVER01\Processor(_Total)\% Idle Time...}

C:\PS> import-counter -path processordata.csv -listset * | foreach {$_.paths}

\\SERVER01\Processor(*)\DPC Rate
\\SERVER01\Processor(*)\% Idle Time
\\SERVER01\Processor(*)\% C3 Time
\\SERVER01\Processor(*)\% Interrupt Time
\\SERVER01\Processor(*)\% C2 Time
\\SERVER01\Processor(*)\% User Time
\\SERVER01\Processor(*)\% C1 Time
\\SERVER01\Processor(*)\% Processor Time
\\SERVER01\Processor(*)\C1 Transitions/sec
\\SERVER01\Processor(*)\% DPC Time
\\SERVER01\Processor(*)\C2 Transitions/sec
\\SERVER01\Processor(*)\% Privileged Time
\\SERVER01\Processor(*)\C3 Transitions/sec
\\SERVER01\Processor(*)\DPCs Queued/sec
\\SERVER01\Processor(*)\Interrupts/sec

Description
-----------
This example shows how to display all the counter paths in a group of imported counter sets.

The first command uses the ListSet parameter to get all of the counter sets that are represented in a counter data file.

The second command gets all of the counter paths from the list set.

Example 5

C:\PS>import-counter -path .\disk.blg | format-table timestamp

C:\PS> $start = [datetime]"7/9/2008 3:47:00 PM"
C:\PS> $end = [datetime]"7/9/2008 3:47:59 PM"

C:\PS> $t-data = import-counter -path disk.blg -starttime $start -endtime $end

This example imports only the counter data that has a time stamp between the starting an ending ranges specified in the command.

The first command lists the time stamps of all of the data in the ProcessorData.blg file.

The second and third commands save particular time stamps in the $start and $end variables. The strings are cast to DateTime objects.

The fourth command uses Import-Counter to get only counter data that has a time stamp between the start and end times (inclusive). The command uses the StartTime and EndTime parameters to specify the range.

Example 6

C:\PS>import-counter -path disk.blg -maxSamples 5

C:\PS> (import-counter -path disk.blg)[-1 .. -5]

This example shows how to import the five oldest and five newest samples from a performance counter log file.

The first command uses the Import-Counter cmdlet to import data from the Disk.blg file. The command uses the MaxSamples parameter to limit the import to five counter samples. This command gets the first (oldest) five samples in the file.

The second command uses array notation and the Windows PowerShell range operator (..) to get the last five counter samples from the file. These are the five newest samples.

Example 7

C:\PS>import-counter D:\Samples\memory.blg -summary

PS C:\ps-test> import-counter D:\Samples\memory.blg -summary

OldestRecord            NewestRecord            SampleCount
------------            ------------            -----------
7/10/2008 2:59:18 PM    7/10/2008 3:00:27 PM    1000

Description
-----------
This command uses the Summary parameter to get a summary of the counter data from the Memory.blg file.

Example 8

C:\PS>$counters = import-counter olddata.blg -ListSet * | foreach {$_.PathsWithInstances}

get-counter -counter $counters -maxSamples 20 | export-counter c:\Logs\newdata.blg

This example updates a performance counter log file.

The first command uses the ListSet parameter of Import-Counter to get the counters in OldData.blg, an existing counter log file. The command uses a pipeline operator (|) to send the data to a Foreach-Object command that gets only the values of the PathsWithInstances property of each object.

The second command uses those same counters in a new Get-Counter command to get a current sample, and export it to the NewData.blg file.

Example 9

C:\PS>$counters = "d:\test\pdata.blg", "d:\samples\netlog.blg" | import-counter

This command imports performance log data from two logs and saves the data in the $counters variable. The command uses a pipeline operator to send performance log paths to Import-Counter.

Notice that each path is enclosed in quotation marks and that the paths are separated from each other by a comma.

See Also

  • Get-Counter
  • Export-Counter


Import-CSV

Converts object properties in a comma-separated value (CSV) file into CSV versions of the original objects.

Syntax

Import-CSV [[-Delimiter] <char>] [-Path] <string[]> [-Header <string[]>] [<CommonParameters>]

Import-CSV -UseCulture [-Path] <string[]> [-Header <string[]>] [<CommonParameters>]

Description

The Import-CSV cmdlet creates objects from CSV variable-length files that are generated by the Export-CSV cmdlet.

You can use the parameters of the Import-CSV cmdlet to specify the column header row, which determines the property names of the resulting objects; to specify the item delimiter; or to direct Import-CSV to use the list separator for the current culture as the item delimiter.

The objects that Import-CSV creates are CSV versions of the original objects. The property values of the CSV objects are string versions of the property values of the original objects. The CSV versions of the objects do not have any methods.

You can also use the ConvertTo-CSV and ConvertFrom-CSV cmdlets to convert objects to CSV strings (and back). These cmdlets are the same as the Export-CSV and Import-CSV cmdlets, except that they do not save the CSV strings in a file.

Parameters

-Delimiter <char>

Specifies the delimiter that separates the property values in the CSV file. The default is a comma (,). Enter a character, such as a colon (:). To specify a semicolon (;), enclose it in quotation marks.

If you specify a character other than the actual string delimiter in the file, Import-CSV cannot create objects from the CSV strings. Instead, it returns the strings.

Required? | false
Position? | 2
Default Value | ,
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Header <string[]>

Specifies an alternate column header row for the imported file. The column header determines the names of the properties of the object that Import-CSV creates.

Enter a comma-separated list of the column headers. Enclose each item in quotation marks (single or double). Do not enclose the header string in quotation marks. If you enter fewer column headers than there are columns, the remaining columns will have no header. If you enter more headers than there are columns, the extra headers are ignored.

When using the Header parameter, delete the original header row from the CSV file. Otherwise, Import-CSV creates an extra object from the items in the header row.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the CSV file to import. You can also pipe a path to Import-CSV.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-UseCulture

Use the list separator for the current culture as the item delimiter. The default is a comma (,).

To find the list separator for a culture, use the following command: (Get-Culture).TextInfo.ListSeparator. If you specify a character other than the delimiter used in the CSV strings, ConvertFrom-CSV cannot create objects from the CSV strings. Instead, it returns the strings.

Required? | true
Position? | named
Default Value | Comma
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Import-CSV.
Outputs | Object. Import-CSV returns the objects described by the content in the CSV file.

Notes

Because the imported objects are CSV versions of the object type, they are not recognized and formatted by the Windows PowerShell type formatting entries that format the non-CSV versions of the object type.

In the CSV file, each object is represented by a comma-separated list of the property values of the object. The property values are converted to strings (by using the ToString() method of the object), so they are generally represented by the name of the property value. Export-CSV does not export the methods of the object.

Example 1

C:\PS>get-process | export-csv processes.csv

C:\PS> $p = import-CSV processes.csv

C:\PS> $p | get-member

TypeName: CSV:System.Diagnostics.Process

Name                       MemberType   Definition
----                       ----------   ----------
Equals                     Method       System.Boolean Equals(Object obj)
GetHashCode                Method       System.Int32 GetHashCode()
GetType                    Method       System.Type GetType()
ToString                   Method       System.String ToString()
BasePriority               NoteProperty System.String BasePriority=8
Company                    NoteProperty System.String Company=Microsoft Corporation
...

C:\PS> $p | out-gridview

Description
-----------
This example shows how to export and then import a CSV file of Microsoft .NET Framework objects.

The first command uses the Get-Process cmdlet to get the process on the local computer. It uses a pipeline operator (|) to send the process objects to the Export-CSV cmdlet, which exports the process objects to the Processes.csv file in the current directory.

The second command uses the Import-CSV cmdlet to import the processes in the Import-CSV file. Then it saves the resulting process objects in the $p variable.

The third command uses a pipeline operator to pipe the imported objects to the Get-Member cmdlets. The result shows that they are CSV:System.Diagnostic.Process objects, not the System.Diagnostic.Process objects that Get-Process returns.

Also, because there is no entry type in the formatting files for the CSV version of the process objects, these objects are not formatted in the same way that standard process objects are formatted.

To display the objects, use the formatting cmdlets, such as Format-Table and Format-List, or pipe the objects to Out-GridView.

Example 2

C:\PS>get-process | export-csv processes.csv -Delimiter :

C:\PS> $p = import-csv processes.csv -Delimiter :

This example shows how to use the Delimiter parameter of Import-CSV. In this example, the processes are exported to a file that uses a colon (:) as a delimiter.

When importing, the Import-CSV file uses the Delimiter parameter to indicate the delimiter that is used in the file.

Example 3

C:\PS>$p = import-csv processes.csv -UseCulture

C:\PS> (get-culture).textinfo.listseparator

,

Description
-----------
This example shows how to use the UseCulture parameter of Import-CSV.

The first command imports the objects in the Processes.csv file into the $p variable. It uses the UseCulture parameter to direct Import-CSV to use the list separator defined for the current culture.

The second command displays the list separator for the current culture. It uses the Get-Culture cmdlet to get the current culture. It uses the dot (.) method to get the TextInfo property of the current culture and the ListSeparator property of the object in TextInfo. In this example, the command returns a comma.

Example 4

C:\PS>start-job -scriptblock { get-process } | export-csv jobs.csv

C:\PS> $header = "MoreData","StatusMessage","Location","Command","State","Finished","InstanceId","SessionId","Name","ChildJobs","Output","Error","Progress","Verbose","Debug","Warning","StateChanged"

# Delete header from file
C:\PS> $a = (get-content jobs.csv)
C:\PS> $a = $a[0], $a[2..($a.count - 1)]
C:\PS> $a > jobs.csv

C:\PS> $j = import-csv jobs.csv -header $header

C:\PS> $j

MoreData      : True
StatusMessage :
Location      : localhost
Command       : get-process
State         : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : 135bdd25-40d6-4a20-bd68-05282a59abd6
SessionId     : 1
Name          : Job1
ChildJobs     : System.Collections.Generic.List`1[System.Management.Automation.Job]
Output        : System.Management.Automation.PSDataCollection`1[System.Management.Automation.PSObject]
Error         : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ErrorRecord]
Progress      : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ProgressRecord]
Verbose       : System.Management.Automation.PSDataCollection`1[System.String]
Debug         : System.Management.Automation.PSDataCollection`1[System.String]
Warning       : System.Management.Automation.PSDataCollection`1[System.String]
StateChanged  :

Description
-----------
This example shows how to use the Header parameter of Import-CSV to change the names of properties in the resulting imported object.

The first command uses the Start-Job cmdlet to start a background job that runs a Get-Process command on the local computer. A pipeline operator (|) sends the resulting job object to the Export-CSV cmdlet, which converts the job object to CSV format. An assignment operator (=) saves the resulting CSV in the Jobs.csv file.

The second command saves a header in the $header variable. Unlike the default header, this header uses "MoreData" instead of "HasMoreData" and "State" instead of "JobStateInfo".

The next three commands delete the original header (the second line) from the Jobs.csv file.

The sixth command uses the Import-CSV cmdlet to import the Jobs.csv file and convert the CSV strings into a CSV version of the job object. The command uses the Header parameter to submit the alternate header. The results are stored in the $j variable.

The seventh command displays the object in the $j variable. The resulting object has "MoreData" and "State" properties, as shown in the command output.

Example 5

C:\PS>".\processes.csv" | import-csv

This command imports the objects from the Processes.csv file.

See Also

  • Export-CSV
  • ConvertTo-CSV
  • ConvertFrom-CSV


Import-LocalizedData

Imports language-specific data into scripts and functions based on the UI culture that is selected for the operating system.

Syntax

Import-LocalizedData [-BindingVariable] <string> [[-UICulture] <string>] [-BaseDirectory <string>] [-FileName <string>] [-SupportedCommand <string[]>] [<CommonParameters>]

Description

The Import-LocalizedData cmdlet dynamically retrieves strings from a subdirectory whose name matches the UI language set for the current user of the operating system. It is designed to enable scripts to display user messages in the UI language selected by the current user.

Import-LocalizedData imports data from .psd1 files in language-specific subdirectories of the script directory and saves them in a local variable that is specified in the command. The cmdlet selects the subdirectory and file based on the value of the $PSUICulture automatic variable. When you use the local variable in the script to display a user message, the message appears in the user's UI language.

You can use the parameters of Import-LocalizedData to specify an alternate UI culture, path, and file name, to add supported commands, and to suppress the error message that appears if the .psd1 files are not found.

The Import-LocalizedData cmdlet supports script internationalization in Windows PowerShell 2.0. This initiative aims to better serve users worldwide by making it easy for scripts to display user messages in the UI language of the current user. For more information about this and about the format of the .psd1 files, see about_Script_Internationalization.

Parameters

-BaseDirectory <string>

Specifies the base directory where the .psd1 files are located. The default is the directory where the script is located. Import-LocalizedData searches for the .psd1 file for the script in a language-specific subdirectory of the base directory.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-BindingVariable <string>

Specifies a variable into which the text strings are imported. Enter a variable name without a dollar sign ($).

When using Import-LocalizedData to replace default text strings specified in the DATA section of a script, assign the DATA section to a variable and enter the name of the DATA section variable in the value of the BindingVariable parameter. Then, when Import-LocalizedData saves the imported content in the BindingVariable, the imported data will replace the default text strings. If you are not specifying default text strings, you can select any variable name.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FileName <string>

Specifies the name of the .psd1 file to be imported. Enter a file name without the .psd1 file name extension.

The default is the name of the script. For example, if the script is FindFiles.ps1, Import-LocalizedData searches for FindFiles.psd1. You can use this parameter to direct Import-LocalizedData to search for a different .psd1 file.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SupportedCommand <string[]>

Specifies cmdlets and functions that generate only data.

Use this parameter to include cmdlets and functions that you have written or tested. For more information, see about_Script_Internationalization.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UICulture <string>

Specifies an alternate UI culture. The default is the value of the $PsUICulture automatic variable. Enter a UI culture in "<language>-<region>" format, such as en-US, de-DE, or ar-SA.

The value of the UICulture parameter determines the language-specific subdirectory (within the base directory) from which Import-LocalizedData gets the .psd1 file for the script.

The cmdlet searches for a subdirectory with the same name as the value of the UICulture parameter or the $PsUICulture automatic variable, such as "de-DE" or "ar-SA". If it cannot find the directory, or the directory does not contain a .psd1 file for the script, it searches for a subdirectory with the name of the language code, such as "de" or "ar". If it cannot find the subdirectory or .psd1 file, the command fails and the data is displayed in the default language specified in the script.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Collections.Hashtable Import-LocalizedData saves the hash table in the variable that is specified by the value of the BindingVariable parameter.

Notes

Before using Import-LocalizedData, localize your user messages. Format the messages for each locale (UI culture) in a hash table of key/value pairs, and save the hash table in a file with the same name as the script and a .psd1 file name extension. Create a directory under the script directory for each supported UI culture, and then save the .psd1 file for each UI culture in the directory with the UI culture name.

For example, localize your user messages for the de-DE locale and format them in a hash table. Save the hash table in a <ScriptName>.psd1 file. Then create a de-DE subdirectory under the script directory, and save the de-DE <ScriptName>.psd1 file in the de-DE subdirectory. Repeat this method for each locale that you support.

Import-LocalizedData performs a structured search for the localized user messages for a script.

Import-LocalizedData begins the search in the directory where the script file is located (or the value of the BaseDirectory parameter). It then searches within the base directory for a subdirectory with the same name as the value of the $PsUICulture variable (or the value of the UICulture parameter), such as "de-DE" or "ar-SA". Then, it searches in that subdirectory for a .psd1 file with the same name as the script (or the value of the FileName parameter).

If Import-LocalizedData cannot find a subdirectory with the name of the UI culture, or the subdirectory does not contain a .psd1 file for the script, it searches for a .psd1 file for the script in a subdirectory with the name of the language code, such as "de" or "ar". If it cannot find the subdirectory or .psd1 file, the command fails, the data is displayed in the default language in the script, and an error message is displayed explaining that the data could not be imported. To suppress the message and fail gracefully, use the ErrorAction common parameter with a value of SilentlyContinue.

If Import-LocalizedData finds the subdirectory and the .psd1 file, it imports the hash table of user messages into the value of the BindingVariable parameter in the command. Then, when you display a message from the hash table in the variable, the localized message is displayed.

For more information, see about_Script_Internationalization.

Example 1

C:\PS>import-localizeddata -bindingVariable messages

This command imports text strings into the $messages variable. It uses all of the default values for the cmdlet parameters.

If the command is included in the Archives.ps1 script in the C:\test directory, and the value of the $PsUICulture automatic variable is zh-CN, Import-LocalizedData imports the Archives.psd1 file in the C:\test\zh-CN directory.

Example 2

C:\PS>import-localizeddata -bindingVariable msgTbl -uiculture ar-SA -filename Simple -baseDirectory C:\Data\Localized

This command imports text strings into the $msgTbl  variable of a script.

It uses the UICulture parameter to direct the cmdlet to import data from the Simple.psd1 file in the ar-SA subdirectory of C:\Data\Localized.

Example 3

C:\PS># In C:\Test\en-US\test.psd1:

ConvertFrom-StringData @'
 # English strings
Msg1 = "The Name parameter is missing from the command."
Msg2 = "This command requires the credentials of a member of the Administrators group on the computer."
Msg3 = "Use $_ to represent the object that is being processed."
'@

# In C:\Test\Test.ps1

import-localizeddata -bindingvariable messages
write-host $messages.msg2

# In Windows PowerShell

C:\PS> .\test.ps1
This command requires the credentials of a member of the Administrators group on the computer.

Description
-----------
This example shows how to use localized data in a simple script.

The first part of the example shows the contents of the Test.psd1 file. It contains a ConvertFrom-StringData command that converts a series of named text strings into a hash table. The test.psd1 file is located in the en-US subdirectory of the C:\Test directory that contains the script.

The second part of the example shows the contents of the Test.ps1 script. It contains an Import-LocalizedData command that imports the data from the matching .psd1 file into the $Messages variable and a Write-Host command that writes one of the messages in the $Messages variable to the host program.

The last part of the example runs the script. The output shows that it displays the correct user message in the UI language set for the current user of the operating system.

Example 4

C:\PS># In TestScript.ps1

$UserMessages = DATA {
    ConvertFrom-StringData @'
    # English strings
        Msg1 = "Enter a name."
        Msg2 = "Enter your employee ID."
        Msg3 = "Enter your building number."
'@ }

Import-LocalizedData -bindingVariable UserMessages

$UserMessages.Msg1
...

Description
-----------
This example shows how to use Import-LocalizedData to replace default text strings defined in the DATA section of a script.

In this example, the DATA section of the TestScript.ps1 script contains a ConvertFrom-StringData command that converts the contents of the DATA section to a hash table and stores in the value of the $UserMessages variable.

The script also includes an Import-LocalizedData command, which imports a hash table of translated text strings from the TestScript.psd1 file in the subdirectory specified by the value of the $PsUICulture variable. If the command finds the .psd1 file, it saves the translated strings from the file in the value of the same $UserMessages variable, overwriting the hash table saved by the DATA section logic.

The third command displays the first message in the $UserMessages variable.

If the Import-LocalizedData command finds a .psd1 file for the $PsUICulture language, the value of the $UserMessages variable contains the translated text strings. If the command fails for any reason, the command displays the default text strings defined in the DATA section of the script.

Example 5

C:\PS># In Day1.ps1
Import-LocalizedData -bindingVariable Day
Day.MessageDate

# In Day2.ps1
Import-LocalizedData -bindingVariable Day -errorAction:silentlycontinue
Day.MessageDate

C:\PS> .\Day1.ps1

Import-LocalizedData : Cannot find PowerShell data file 'Day1.psd1' in directory 'C:\ps-test\fr-BE\' or any parent culture directories.
At C:\ps-test\Day1.ps1:17 char:21
+ Import-LocalizedData <<<<  Day
Today is Tuesday

C:\PS> .\Day2.ps1

Today is Tuesday

Description
-----------
This example shows how to suppress the error messages that appear when Import-LocalizedData cannot find the directories that match the user's UI culture or cannot find a .psd1 file for the script in those directories.

You can use the ErrorAction common parameter with a value of "SilentlyContinue" to suppress the error message. This is especially useful when you have provided user messages in a default or "fallback" language, and no error message is needed.

This example compares two scripts, Day1.ps1 and Day2.ps1, that include an Import-LocalizedData command. The scripts are identical, except that Day2 uses the ErrorAction common parameter with a value of SilentlyContinue.

The sample output shows the results of running both scripts when the UI culture is set to fr-BE and there are no matching files or directories for that UI culture. Day1.ps1 displays an error message and English output. Day2.ps1 just displays the English output.

See Also

  • about_Script_Internationalization


Import-Module

Adds modules to the current session.

Syntax

Import-Module [-Name] <string[]> [-Alias <string[]>] [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <string[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]>] [-Version <Version>] [<CommonParameters>]

Import-Module [-Assembly] <Assembly[]> [-Alias <string[]>] [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <string[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]>] [-Version <Version>] [<CommonParameters>]

Import-Module [-ModuleInfo] <PSModuleInfo[]> [-Alias <string[]>] [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <string[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]>] [-Version <Version>] [<CommonParameters>]

Description

The Import-Module cmdlet adds one or more modules to the current session.

A module is a package that contains members (such as cmdlets, providers, scripts, functions, variables, and other tools and files) that can be used in Windows PowerShell. After a module is imported, you can use the module members in your session.

To import a module, use the Name, Assembly, or ModuleInfo parameter to identify the module to import. By default, Import-Module imports all members that the module exports, but you can use the Alias, Function, Cmdlet, and Variable parameters to restrict the members that are imported.

Import-Module imports a module only into the current session. To import the module into all sessions, add an Import-Module command to your Windows PowerShell profile. For more information about profiles, see about_Profiles.

For more information about modules, see about_Modules.

Parameters

-Alias <string[]>

Imports only the specified aliases from the module into the current session. Enter a comma-separated list of aliases. Wildcard characters are permitted.

Some modules automatically export selected aliases into your session when you import the module. This parameter lets you select from among the exported aliases.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-ArgumentList <Object[]>

Specifies arguments (parameter values) that are passed to a script module during the Import-Module command. This parameter is valid only when you are importing a script module.

You can also refer to ArgumentList by its alias, "args". For more information, see about_Aliases.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsCustomObject

Returns a custom object with members that represent the imported module members. This parameter is valid only for script modules.

When you use the AsCustomObject parameter, Import-Module imports the module members into the session and then returns a PSCustomObject object instead of a PSModuleInfo object. You can save the custom object in a variable and use dot notation to invoke the members.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Assembly <Assembly[]>

Imports the cmdlets and providers implemented in the specified assembly objects. Enter a variable that contains assembly objects or a command that creates assembly objects. You can also pipe an assembly object to Import-Module.

When you use this parameter, only the cmdlets and providers implemented by the specified assemblies are imported. If the module contains other files, they are not imported, and you might be missing important members of the module. Use this parameter for debugging and testing the module, or when you are instructed to use it by the module author.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Cmdlet <string[]>

Imports only the specified cmdlets from the module into the current session. Enter a list of cmdlets. Wildcard characters are permitted.

Some modules automatically export selected cmdlets into your session when you import the module. This parameter lets you select from among the exported cmdlets.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Force

Re-imports a module and its members, even if the module or its members have an access mode of read-only.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Function <string[]>

Imports only the specified functions from the module into the current session. Enter a list of functions. Wildcard characters are permitted.

Some modules automatically export selected functions into your session when you import the module. This parameter lets you select from among the exported functions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Global

When used in a script module (.psm1), this parameter imports modules into the global session state.

This parameter is effective only when it appears in a script module. Otherwise, it is ignored.

By default, the commands in a script module, including commands from nested modules, are imported into the caller's session state. To restrict the commands that a module exports, use an Export-ModuleMember command in the script module.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ModuleInfo <PSModuleInfo[]>

Specifies module objects to import. Enter a variable that contains the module objects, or a command that gets the module objects, such as a "Get-Module -listavailable" command. You can also pipe module objects to Import-Module.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of the modules to import. Enter the name of the module or the name of a file in the module, such as a .psd1, .psm1, .dll, or ps1 file. File paths are optional. Wildcards are not permitted. You can also pipe module names and file names to Import-Module.

If you omit a path, Import-Module looks for the module in the paths saved in the PSModulePath environment variable ($env:PSModulePath).

Specify only the module name whenever possible. When you specify a file name, only the members that are implemented in that file are imported. If the module contains other files, they are not imported, and you might be missing important members of the module.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-PassThru

Returns objects that represent the modules that were imported. By default, this cmdlet does not generate any output.

Notes

-- When you pipe the output of a "Get-Module -listavailable" command to an Import-Module command with the PassThru parameter, Import-Module returns the object that Get-Module passed to it without updating the object. As a result, the Exported and NestedModules properties are not yet populated.

-- When you use the Prefix parameter to specify a prefix for the member, the prefix does not appear in the member names in the properties of the module object. The object records what was exported before the prefix was applied.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Prefix <string>

Adds the specified prefix to the nouns in the names of imported module members.

Use this parameter to avoid name conflicts that might occur when different members in the session have the same name. This parameter does not change the module, and it does not affect files that the module imports for its own use (known as "nested modules"). It affects only the names of members in the current session.

For example, if you specify the prefix "UTC" and then import a Get-Date cmdlet, the cmdlet is known in the session as Get-UTCDate, and it is not confused with the original Get-Date cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Variable <string[]>

Imports only the specified variables from the module into the current session. Enter a list of variables. Wildcard characters are permitted.

Some modules automatically export selected variables into your session when you import the module. This parameter lets you select from among the exported variables.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Version <Version>

Specifies the version of the module to import. Use this parameter when you have different versions of the same module on your system.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String, System.Management.Automation.PSModuleInfo, System.Reflection.Assembly You can pipe a module name, module object, or assembly object to Import-Module.
Outputs | None, System.Management.Automation.PSModuleInfo, or System.Management.Automation.PSCustomObject By default, Import-Module does not generate any output. If you use the PassThru parameter, it generates a System.Management.Automation.PSModuleInfo object that represents the module. If you use the AsCustomObject parameter, it generates a PSCustomObject object.

Notes

You can also refer to Import-Module by its alias, "ipmo". For more information, see about_Aliases.

Before you can import a module, the module directory must be copied to a directory that is accessible to your local computer. For more information, see about_Modules.

Module members run in their own private module session state, so the commands that they use for internal processing do not affect your session state.

If you import members with the same name and the same type into your session, Windows PowerShell uses the member imported last by default. Variables and aliases are replaced, and the originals are not accessible. Functions, cmdlets and providers are merely "shadowed" by the new members, and they can be accessed by qualifying the command name with the name of its snap-in, module, or function path.

To update the formatting data for commands that have been imported from a module, use the Update-FormatData cmdlet. Update-FormatData also updates the formatting data for commands in the session that were imported from modules. If the formatting file for a module changes, you can run an Update-FormatData command to update the formatting data for imported commands. You do not need to import the module again.

To import a module that is created by Import-PSSession or Export-PSSession, the execution policy in the current session cannot be Restricted or AllSigned, because the modules that Import-PSSession and Export-PSSession create contains unsigned script files that are prohibited by these policies. To use Import-Module without changing the execution policy for the local computer, use the Scope parameter of Set-ExecutionPolicy to set a less restrictive execution policy for a single process.

Example 1

C:\PS>import-module -name BitsTransfer

This command imports the members of the BitsTransfer module into the current session.

The Name parameter name (-Name) is optional and can be omitted.

By default, Import-Module does not generate any output when it imports a module. To request output, use the PassThru or AsCustomObject parameter, or the Verbose common parameter.

Example 2

C:\PS>get-module -listAvailable | import-module

This command imports all available modules in the path specified by the PSModulePath environment variable ($env:psmodulepath) into the current session.

Example 3

C:\PS>$m = get-module -ListAvailable BitsTransfer, ServerBackup

C:\PS> import-module -moduleInfo $m

These commands import the members of the BitsTransfer and ServerBackup modules into the current session.

The first command uses the Get-Module cmdlet to get PSModuleInfo objects that represent the BitsTransfer and ServerBackup modules. It saves the objects in the $m variable. The ListAvailable parameter is required when you are getting modules that are not yet imported into the session.

The second command uses the ModuleInfo parameter of Import-Module to import the modules into the current session.

These commands are equivalent to using a pipeline operator (|) to send the output of a Get-Module command to Import-Module.

Example 4

C:\PS>import-module -name c:\ps-test\modules\test -verbose

VERBOSE: Loading module from path 'C:\ps-test\modules\Test\Test.psm1'.
VERBOSE: Exporting function 'my-parm'.
VERBOSE: Exporting function 'get-parm'.
VERBOSE: Exporting function 'get-spec'.
VERBOSE: Exporting function 'get-specDetails'.

Description
-----------
This command uses an explicit path to identify the module to import.

It also uses the Verbose common parameter to get a list of the items imported from the module. Without the Verbose, PassThru, or AsCustomObject parameter, Import-Module does not generate any output when it imports a module.

Example 5

C:\PS>import-module BitsTransfer -cmdlet Add-BitsTransferFile, Get-BitsTransfer

C:\PS> get-module BitsTransfer

Name              : BitsTransfer
Path              : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BitsTransfer\BitsTransfer.psd1
Description       :
Guid              : 8fa5064b-8479-4c5c-86ea-0d311fe48875
Version           : 1.0.0.0
ModuleBase        : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BitsTransfer
ModuleType        : Manifest
PrivateData       :
AccessMode        : ReadWrite
ExportedAliases   : {}
ExportedCmdlets   : {[Add-BitsTransfer, Add-BitsTransfer], [Complete-BitsTransfer, Complete-BitsTransfer], [Get-BitsTransfer, Get-BitsTransfer], [Rem
                    ove-BitsTransfer, Remove-BitsTransfer]...}
ExportedFunctions : {}
ExportedVariables : {}
NestedModules     : {Microsoft.BackgroundIntelligentTransfer.Management}

C:\PS> get-command -module BitsTransfer

CommandType Name                Definition
----------- ----                ----------
Cmdlet      Add-BitsTransfer    Add-BitsTransfer [-BitsJob] <BitsJob[]> [-Source] <String[]> [[-Destination] <String[]>] [-Verbose] [-Debug] [-ErrorA...
Cmdlet      Get-BitsTransfer    Get-BitsTransfer [[-Name] <String[]>] [-AllUsers] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningActi...

Description
-----------
This example shows how to restrict the module members that are imported into the session and the effect of this command on the session.

The first command imports only the Add-BitsTransfer and Get-BitsTransfer cmdlets from the BitsTransfer module. The command uses the Cmdlet parameter to restrict the cmdlets that the module imports. You can also use the Alias, Variable, and Function parameters to restrict other members that a module imports.

The second command uses the Get-Module cmdlet to get the object that represents the BitsTransfer module. The ExportedCmdlets property lists all of the cmdlets that the module exports, even when they were not all imported.

The third command uses the Module parameter of the Get-Command cmdlet to get the commands that were imported from the BitsTransfer module. The results confirm that only the Add-BitsTransfer and Get-BitsTransfer cmdlets were imported.

Example 6

C:\PS>import-module BitsTransfer -prefix PS -passthru

Name              : bitstransfer
Path              : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\bitstransfer\bitstransfer.psd1
Description       :
Guid              : 8fa5064b-8479-4c5c-86ea-0d311fe48875
Version           : 1.0.0.0
ModuleBase        : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\bitstransfer
ModuleType        : Manifest
PrivateData       :
AccessMode        : ReadWrite
ExportedAliases   : {}
ExportedCmdlets   : {[Add-BitsTransfer, Add-BitsTransfer], [Remove-BitsTransfer, Remove-BitsTransfer], [Complete-BitsTransfer, Complete-BitsTransfer]
                    , [Get-BitsTransfer, Get-BitsTransfer]...}
ExportedFunctions : {}
ExportedVariables : {}
NestedModules     : {Microsoft.BackgroundIntelligentTransfer.Management}

C:\PS> get-command -module bitstransfer

CommandType     Name                        Definition
-----------     ----                        ----------
Cmdlet          Add-PSBitsTransfer          Add-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Source] <String[]> ...
Cmdlet          Complete-PSBitsTransfer     Complete-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Verbose] [-Deb...
Cmdlet          Get-PSBitsTransfer          Get-PSBitsTransfer [[-Name] <String[]>] [-AllUsers] [-Verbose] ...
Cmdlet          Remove-PSBitsTransfer       Remove-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Verbose] [-Debug...
Cmdlet          Resume-PSBitsTransfer       Resume-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Asynchronous] [-...
Cmdlet          Set-PSBitsTransfer          Set-PSBitsTransfer [-BitsJob] <BitsJob[]> [-DisplayName <String...
Cmdlet          Start-PSBitsTransfer        Start-PSBitsTransfer [[-Source] <String[]>] [[-Destination] <St...
Cmdlet          Suspend-PSBitsTransfer      Suspend-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Verbose] [-Debu...

Description
-----------
These commands import the BitsTransfer module into the current session, add a prefix to the member names, and then display the prefixed member names.

The first command uses the Import-Module cmdlet to import the BitsTransfer module. It uses the Prefix parameter to add the PS prefix to all members that are imported from the module and the PassThru parameter to return a module object that represents the imported module.

The module object that the command returns has an ExportedCmdlets property that lists the exported members. The prefix does not appear in the cmdlet names, because it is applied after the members are exported (but before they are imported).

The second command uses the Get-Command cmdlet to get the members that have been imported from the module. It uses the Module parameter to specify the module. The output shows that the module members were correctly prefixed.

The prefix that you use applies only to the members in the current session. It does not change the module.

Example 7

C:\PS>get-module -list | format-table -property name, moduletype -auto

Name          ModuleType
----          ----------
Show-Calendar     Script
BitsTransfer    Manifest
PSDiagnostics   Manifest
TestCmdlets       Script

C:\PS> $a = import-module -name Show-Calendar -asCustomObject

C:\PS> $a | get-member

   TypeName: System.Management.Automation.PSCustomObject

Name          MemberType   Definition
----          ----------   ----------
Equals        Method       bool Equals(System.Object obj)
GetHashCode   Method       int GetHashCode()
GetType       Method       type GetType()
ToString      Method       string ToString()
Show-Calendar ScriptMethod System.Object Show-Calendar();

C:\PS> $a."show-calendar"()

Description
-----------
These commands demonstrate how to get and use the custom object that Import-Module returns.

Custom objects include synthetic members that represent each of the imported module members. For example, the cmdlets and functions in a module are converted to script methods of the custom object.

Custom objects are very useful in scripting. They are also useful when several imported objects have the same names. Using the script method of an object is equivalent to specifying the fully qualified name of an imported member, including its module name.

The AsCustomObject parameter can be used only with a script module, so the first task is to determine which of the available modules is a script module.

The first command uses the Get-Module cmdlet to get the available modules. The command uses a pipeline operator (|) to pass the module objects to the Format-Table cmdlet, which lists the Name and ModuleType of each module in a table.

The second command uses the Import-Module cmdlet to import the Show-Calendar script module. The command uses the AsCustomObject parameter to request a custom object. The command saves the resulting custom object in the $a variable.

The third command uses a pipeline operator to send the $a variable to the Get-Member cmdlet, which gets the properties and methods of the PSCustomObject in $a. The output shows a Show-Calendar script method.

The last command uses the Show-Calendar script method. The method name must be enclosed in quotation marks, because it includes a hyphen.

Example 8

C:\PS>import-module BitsTransfer

C:\PS> import-module BitsTransfer -force -prefix PS

This example shows how to use the Force parameter of Import-Module when you are re-importing a module into the same session.

The first command imports the BitsTransfer module. The second command imports the module again, this time using the Prefix parameter.

The second command also includes the Force parameter, which removes the module and then imports it again. Without this parameter, the session would include two copies of each BitsTransfer cmdlet, one with the standard name and one with the prefixed name.

Example 9

C:\PS>get-date

Saturday, September 12, 2009 6:47:04 PM

C:\PS> import-module TestModule

C:\PS> get-date
09255

C:\PS> get-command get-date | format-table -property commandtype, name, pssnapin, module -auto

CommandType  Name       pssnapin                       Module
-----------  ----       --------                       ------
   Function  Get-Date                                  TestModule
     Cmdlet  Get-Date   Microsoft.PowerShell.Utility

C:\PS> Microsoft.PowerShell.Utility\get-date

Saturday, September 12, 2009 6:33:23 PM

Description
-----------
This example shows how to run commands that have been hidden by imported commands.

The first command run the Get-Date cmdlet that comes with Windows PowerShell. It returns a DateTime object with the current date.

The second command imports the TestModule module. This module includes a function named Get-Date that returns the Julian date.

The third command runs the Get-Date command again. Because functions take precedence over cmdlets, the Get-Date function from the TestModule module ran, instead of the Get-Date cmdlet.

The fourth command shows that there are two Get-Date commands in the session, a function from the TestModule module and a cmdlet from the Microsoft.PowerShell.Utility snap-in.

The fifth command runs the hidden cmdlet by qualifying the command name with the snap-in name.

For more information about command precedence in Windows PowerShell, see about_command_precedence.

See Also

  • Get-Module
  • New-Module
  • Remove-Module
  • Export-ModuleMember
  • about_Modules


Import-PSSession

Imports commands from another session into the current session.

Syntax

Import-PSSession [-Session] <PSSession> [[-CommandName] <string[]>] [[-FormatTypeName] <string[]>] [-AllowClobber] [-ArgumentList <Object[]>] [-CommandType {<Alias> | <Function> | <Filter> | <Cmdlet> | <ExternalScript> | <Application> | <Script> | <All>}] [-Module <string[]>] [-Prefix <string>] [<CommonParameters>]

Description

The Import-PSSession cmdlet imports commands (such as cmdlets, functions, and aliases) from a PSSession on a local or remote computer into the current session. You can import any command that Get-Command can find in the PSSession.

Use an Import-PSSession command to import commands from a customized shell, such as a Microsoft Exchange Server shell, or from a session that includes Windows PowerShell modules and snap-ins or other elements that are not in the current session.

To import commands, first use the New-PSSession cmdlet to create a PSSession. Then, use the Import-PSSession cmdlet to import the commands. By default, Import-PSSession imports all commands except for commands that have the same names as commands in the current session. To import all the commands, use the AllowClobber parameter.

You can use imported commands just as you would use any command in the session. When you use an imported command, the imported part of the command runs implicitly in the session from which it was imported. However, the remote operations are handled entirely by Windows PowerShell. You need not even be aware of them, except that you must keep the connection to the other session (PSSession) open. If you close it, the imported commands are no longer available.

Because imported commands might take longer to run than local commands, Import-PSSession adds an AsJob parameter to every imported command. This parameter allows you to run the command as a Windows PowerShell background job. For more information, see about_Jobs.

When you use Import-PSSession, Windows PowerShell adds the imported commands to a temporary module that exists only in your session and returns an object that represents the module. To create a persistent module that you can use in future sessions, use the Export-PSSession cmdlet.

The Import-PSSession cmdlet uses the implicit remoting feature of Windows PowerShell. When you import commands into the current session, they run implicitly in the original session or in a similar session on the originating computer.

Parameters

-AllowClobber

Imports the specified commands, even if they have the same names as commands in the current session.

If you import a command with the same name as a command in the current session, the imported command hides or replaces the original commands. For more information, see about_Command_Precedence.

By default, Import-PSSession does not import commands that have the same name as commands in the current session.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ArgumentList <Object[]>

Imports the variant of the command that results from using the specified arguments (parameter values).

For example, to import the variant of the Get-Item command in the certificate (Cert:) drive in the PSSession in $s, type "import-pssession -session $s -command Get-Item -argumentlist cert:".

Required? | false
Position? | named
Default Value | All command in the PSSession, except for commands with the same names as commands in the current session.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CommandName <string[]>

Imports only the commands with the specified names or name patterns. Wildcards are permitted. Use "CommandName" or its alias, "Name".

By default, Import-PSSession imports all commands from the session, except for commands that have the same names as commands in the current session. This prevents imported commands from hiding or replacing commands in the session. To import all commands, even those that hide or replace other commands, use the AllowClobber parameter.

If you use the CommandName parameter, the formatting files for the commands are not imported unless you use the FormatTypeName parameter. Similarly, if you use the FormatTypeName parameter, no commands are imported unless you use the CommandName parameter.

Required? | false
Position? | 3
Default Value | All commands in the PSSession, except for commands with the same names as commands in the current session.
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-CommandType <CommandTypes>

Imports only the specified types of command objects. The default value is Cmdlet. Use "CommandType" or its alias, "Type".

Valid values are:

-- Alias: The Windows PowerShell aliases in the remote session.

-- All: The cmdlets and functions in the remote session.

-- Application: All the files other than Windows-PowerShell files in the paths that are listed in the Path environment variable ($env:path) in the remote session, including .txt, .exe, and .dll files.

-- Cmdlet: The cmdlets in the remote session. "Cmdlet" is the default.

-- ExternalScript: The .ps1 files in the paths listed in the Path environment variable ($env:path) in the remote session.

-- Filter and Function: The Windows PowerShell functions in the remote session.

-- Script: The script blocks in the remote session.

Required? | false
Position? | named
Default Value | All command in the PSSession, except for commands with the same names as commands in the current session.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FormatTypeName <string[]>

Imports formatting instructions for the specified Microsoft .NET Framework types. Enter the type names. Wildcards are permitted.

The value of this parameter must be the name of a type that is returned by a Get-FormatData command in the session from which the commands are being imported. To get all of the formatting data in the remote session, type *.

If the command does not include either the CommandName or FormatTypeName parameters, Import-PSSession

imports formatting instructions for all .NET Framework types returned by a Get-FormatData command in the remote session.

If you use the FormatTypeName parameter, no commands are imported unless you use the CommandName parameter.

Similarly, if you use the CommandName parameter, the formatting files for the commands are not imported unless you use the FormatTypeName parameter.

Required? | false
Position? | 4
Default Value | Types in the System.Management.Automation namespace
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Module <string[]>

Imports only the commands in the specified Windows PowerShell snap-ins and modules. Enter the snap-in and module names. Wildcards are not permitted.

For more information, see about_PSSnapins and Import-Module.

Required? | false
Position? | named
Default Value | All command in the PSSession, except for commands with the same names as commands in the current session.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Prefix <string>

Adds the specified prefix to the nouns in the names of imported commands.

Use this parameter to avoid name conflicts that might occur when different commands in the session have the same name.

For example, if you specify the prefix "Remote" and then import a Get-Date cmdlet, the cmdlet is known in the session as Get-RemoteDate and it is not confused with the original Get-Date cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Session <PSSession>

Specifies the PSSession from which the cmdlets are imported. Enter a variable that contains a session object or a command that gets a session object, such as a New-PSSession or Get-PSSession command. You can specify only one session. This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to this cmdlet.
Outputs | System.Management.Automation.PSModuleInfo Import-PSSession returns the same module object that New-Module and Get-Module return. However, the imported module is temporary and exists only in the current session. To create a permanent module on disk, use the Export-PSSession cmdlet.

Notes

Import-PSSession relies on the Windows PowerShell remoting infrastructure. To use this cmdlet, the computer must be configured for WS-Management remoting. For more information, see about_Remote and about_Remote_Requirements.

You cannot use Import-PSSession to import variables or Windows PowerShell providers.

When you import commands that have the same names as commands in the current session, the imported commands can hide aliases, functions, and cmdlets in the session and they can replace functions and variables in the session. For more information, see about_Command_Precedence.

Import-PSSession converts all commands into functions before it imports them. As a result, imported commands behave a bit differently than they would if they retained their original command type. For example, if you import a cmdlet from a PSSession and then import a cmdlet with the same name from a module or snap-in, the cmdlet that is imported from the PSSession always runs by default because functions take precedence over cmdlets. Conversely, if you import an alias into a session that has an alias with the same name, the original alias is always used, because aliases take precedence over functions. For more information, see about_Command_Precedence.

Import-PSSession uses the Write-Progress cmdlet to display the progress of the command. You might see the progress bar while the command is running.

To find the commands to import, Import-PSSession uses the Invoke-Command cmdlet to run a Get-Command command in the PSSession. To get formatting data for the commands, it uses the Get-FormatData cmdlet. You might see error messages from Invoke-Command, Get-Command, and Get-FormatData when you run an Import-PSSession command. Also, Import-PSSession cannot import commands from a PSSession that does not include the Get-Command, Get-FormatData, Select-Object, and Get-Help cmdlets.

Imported commands have the same limitations as other remote commands, including the inability to start a program with a user interface, such as Notepad.

Because Windows PowerShell profiles are not run in PSSessions, the commands that a profile adds to a session are not available to Import-PSSession. To import commands from a profile, use an Invoke-Command command to run the profile in the PSSession manually before importing commands.

The temporary module that Import-PSSession creates might include a formatting file, even if the command does not import formatting data. If the command does not import formatting data, any formatting files that are created will not contain formatting data.

To use Import-PSSession, the execution policy in the current session cannot be Restricted or AllSigned, because the module that Import-PSSession creates contains unsigned script files that are prohibited by these policies. To use Import-PSSession without changing the execution policy for the local computer, use the Scope parameter of Set-ExecutionPolicy to set a less restrictive execution policy for a single process.

Example 1

C:\PS>$s = new-pssession -computername Server01

C:\PS> import-pssession -session $s

This command imports all commands from a PSSession on the Server01 computer into the current session, except for commands that have the same names as commands in the current session.

Because this command does not use the CommandName parameter, it also imports all of the formatting data required for the imported commands.

Example 2

C:\PS>$s = new-pssession https://ps.testlabs.com/powershell

C:\PS> import-pssession -session $s -commandname *-test -formatTypeName *

C:\PS> new-test -name test1

C:\PS> get-test test1 | run-test

These commands import the commands with names that end in "-test" from a PSSession into the local session, and then they show how to use an imported cmdlet.

The first command uses the New-PSSession cmdlet to create a PSSession. It saves the PSSession in the $s variable.

The second command uses the Import-PSSession cmdlet to import commands from the PSSession in $s into the current session. It uses the CommandName parameter to specify commands with the Test noun and the FormatTypeName parameter to import the formatting data for the Test commands.

The third and fourth commands use the imported commands in the current session. Because imported commands are actually added to the current session, you use the local syntax to run them. You do not need to use the Invoke-Command cmdlet to run an imported command.

Example 3

C:\PS>$s1 = new-pssession -computername s1

C:\PS> $s2 = new-pssession -computername s2

C:\PS> import-pssession -session s1 -type cmdlet -name New-Test, Get-Test -FormatTypeName *

C:\PS> import-pssession -session s2 -type cmdlet -name Set-Test -FormatTypeName *

C:\PS> new-test Test1 | set-test -runtype full

This example shows that you can use imported cmdlets just as you would use local cmdlets.

These commands import the New-Test and Get-Test cmdlets from a PSSession on the Server01 computer and the Set-Test cmdlet from a PSSession on the Server02 computer.

Even though the cmdlets were imported from different PSSessions, you can pipe an object from one cmdlet to another without error.

Example 4

C:\PS>$s = new-pssession -computername Server01

C:\PS> import-pssession -session $s -commandname *-test* -formattypename *

C:\PS> $batch = new-test -name Batch -asjob

C:\PS> receive-job $batch

This example shows how to run an imported command as a background job.

Because imported commands might take longer to run than local commands, Import-PSSession adds an AsJob parameter to every imported command. The AsJob parameter lets you run the command as a background job.

The first command creates a PSSession on the Server01 computer and saves the PSSession object in the $s variable.

The second command uses Import-PSSession to import the Test cmdlets from the PSSession in $s into the current session.

The third command uses the AsJob parameter of the imported New-Test cmdlet to run a New-Test command as a background job. The command saves the job object that New-Test returns in the $batch variable.

The fourth command uses the Receive-Job cmdlet to get the results of the job in the $batch variable.

Example 5

C:\PS>$s = new-pssession -comp Server01

C:\PS> invoke-command -session $s {import-module TestManagement}

C:\PS> import-pssession -session $s -module TestManagement

This example shows how to import the cmdlets and functions from a Windows PowerShell module on a remote computer into the current session.

The first command creates a PSSession on the Server01 computer and saves it in the $s variable.

The second command uses the Invoke-Command cmdlet to run an Import-Module command in the PSSession in $s.

Typically, the module would be added to all sessions by an Import-Module command in a Windows PowerShell profile, but profiles are not run in PSSessions.

The third command uses the Module parameter of Import-PSSession to import the cmdlets and functions in the module into the current session.

Example 6

C:\PS>import-pssession $s -CommandName Get-Date, SearchHelp  -formatTypeName * -AllowClobber

Name              : tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1zunz.ttf
Path              : C:\Users\User01\AppData\Local\Temp\tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1zunz.ttf\tmp_79468106-4e1d-4d90-af97-1154f9317239_
                    tcw1zunz.ttf.psm1
Description       : Implicit remoting for http://server01.corp.fabrikam.com/wsman
Guid              : 79468106-4e1d-4d90-af97-1154f9317239
Version           : 1.0
ModuleBase        : C:\Users\User01\AppData\Local\Temp\tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1zunz.ttf
ModuleType        : Script
PrivateData       : {ImplicitRemoting}
AccessMode        : ReadWrite
ExportedAliases   : {}
ExportedCmdlets   : {}
ExportedFunctions : {[Get-Date, Get-Date], [SearchHelp, SearchHelp]}
ExportedVariables : {}
NestedModules     : {}

Description
-----------
This example shows that Import-PSSession creates a module in a temporary file on disk. It also shows that all commands are converted into functions before they are imported into the current session.

The command uses the Import-PSSession cmdlet to import a Get-Date cmdlet and a SearchHelp function into the current session.

The Import-PSSession cmdlet returns a PSModuleInfo object that represents the temporary module. The value of the Path property shows that Import-PSSession created a script module (.psm1) file in a temporary location. The ExportedFunctions property shows that the Get-Date cmdlet and the SearchHelp function were both imported as functions.

Example 7

C:\PS>import-pssession $s -CommandName Get-Date -formatTypeName * -AllowClobber

C:\PS> get-command get-date

CommandType   Name       Definition
-----------   ----       ----------
Function      Get-Date   ...
Cmdlet        Get-Date   Get-Date [[-Date] <DateTime>] [-Year <Int32>] [-Month <Int32>]

C:\PS> Get-Date
09074

C:\PS> (get-command -type cmdlet -name get-date).pssnapin.name
Microsoft.PowerShell.Utility

C:\PS> Microsoft.PowerShell.Utility\get-date

Sunday, March 15, 2009 2:08:26 PM

Description
-----------
This example shows how to run a command that is hidden by an imported command.

The first command imports a Get-Date cmdlet from the PSSession in the $s variable. Because the current session includes a Get-Date cmdlet, the AllowClobber parameter is required in the command.

The second command uses the Get-Command cmdlet to get the Get-Date commands in the current session. The output shows that the session includes the original Get-Date cmdlet and a Get-Date function. The Get-Date function runs the imported Get-Date cmdlet in the PSSession in $s.

The third command runs a Get-Date command. Because functions take precedence over cmdlets, Windows PowerShell runs the imported Get-Date function, which returns a Julian date.

The fourth and fifth commands show how to use a qualified name to run a command that is hidden by an imported command.

The fourth command gets the name of the Windows PowerShell snap-in that added the original Get-Date cmdlet to the current session.

The fifth command uses the snap-in-qualified name of the Get-Date cmdlet to run a Get-Date command.

For more information about command precedence and hidden commands, see about_Command_Precedence.

Example 8

C:\PS>import-pssession -session $s -commandName *Item* -AllowClobber

This command imports commands whose names include "Item" from the PSSession in $s. Because the command includes the CommandName parameter but not the FormatTypeData parameter, only the command is imported.

Use this command when you are using Import-PSSession to run a command on a remote computer and you already have the formatting data for the command in the current session.

Example 9

C:\PS>$m = import-pssession -session $s -CommandName *bits* -formattypename *bits*

C:\PS> get-command -module $m

CommandType     Name
-----------     ----
Function        Add-BitsFile
Function        Complete-BitsTransfer
Function        Get-BitsTransfer
Function        Remove-BitsTransfer
Function        Resume-BitsTransfer
Function        Set-BitsTransfer
Function        Start-BitsTransfer
Function        Suspend-BitsTransfer

Description
-----------
This command shows how to use the Module parameter of Get-Command to find out which commands were imported into the session by an Import-PSSession command.

The first command uses the Import-PSSession cmdlet to import commands whose names include "bits" from the PSSession in the $s variable. The Import-PSSession command returns a temporary module, and the command saves the module in the $m variable.

The second command uses the Get-Command cmdlet to get the commands that are exported by the module in the $m variable.

The Module parameter takes a string value, which is designed for the module name. However, when you submit a module object, Windows PowerShell uses the ToString method on the module object, which returns the module name.

The Get-Command command is the equivalent of "get-command $m.name".

See Also

  • about_Command_Precedence
  • New-PSSession
  • Export-PSSession
  • about_Jobs
  • about_PSSessions


Invoke-Command

Runs commands on local and remote computers.

Syntax

Invoke-Command [-ScriptBlock] <scriptblock> [[-ComputerName] <string[]>] [-ApplicationName <string>] [-AsJob] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-Port <int>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-UseSSL] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

Invoke-Command [-FilePath] <string> [[-ComputerName] <string[]>] [-ApplicationName <string>] [-AsJob] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-Port <int>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-UseSSL] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

Invoke-Command [-FilePath] <string> [[-Session] <PSSession[]>] [-AsJob] [-HideComputerName] [-JobName <string>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

Invoke-Command [-FilePath] <string> [[-ConnectionURI] <Uri[]>] [-AllowRedirection] [-AsJob] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

Invoke-Command [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

Invoke-Command [-ScriptBlock] <scriptblock> [[-Session] <PSSession[]>] [-AsJob] [-HideComputerName] [-JobName <string>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

Invoke-Command [-ScriptBlock] <scriptblock> [[-ConnectionURI] <Uri[]>] [-AllowRedirection] [-AsJob] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

Description

The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. With a single Invoke-Command command, you can run commands on multiple computers.

To run a single command on a remote computer, use the ComputerName parameter. To run a series of related commands that share data, create a PSSession (a persistent connection) on the remote computer, and then use the Session parameter of Invoke-Command to run the command in the PSSession.

You can also use Invoke-Command on a local computer to evaluate or run a string in a script block as a command. Windows PowerShell converts the script block to a command and runs the command immediately in the current scope, instead of just echoing the string at the command line.

Before using Invoke-Command to run commands on a remote computer, read about_Remote.

Parameters

-AllowRedirection

Allows redirection of this connection to an alternate URI.

When you use the ConnectionURI parameter, the remote destination can return an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use the AllowRedirection parameter to allow it to redirect the connection.

You can also limit the number of times that the connection is redirected by setting the MaximumConnectionRedirectionCount property of the $PSSessionOption preference variable, or the MaximumConnectionRedirectionCount property of the value of the SessionOption parameter. The default value is 5. For more information, see the description of the SessionOption parameter and the help topic for the New-PSSessionOption cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ApplicationName <string>

Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the ConnectionURI parameter in the command.

The default value is the value of the $PSSessionApplicationName preference variable on the local computer. If this preference variable is not defined, the default value is WSMAN. This value is appropriate for most uses. For more information, see about_Preference_Variables.

The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the URLPrefix property of a listener on the remote computer.

Required? | false
Position? | named
Default Value | WSMAN
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-ArgumentList <Object[]>

Supplies the values of local variables in the command. The variables in the command are replaced by these values before the command is run on the remote computer. Enter the values in a comma-separated list. Values are associated with variables in the order that they are listed. The alias for ArgumentList is "Args".

The values in ArgumentList can be actual values, such as "1024", or they can be references to local variables, such as "$max".

To use local variables in a command, use the following command format:

{param($<name1>[, $<name2>]...) <command-with-local-variables>} -ArgumentList <value | $local-variable>

The "param" keyword lists the local variables that are used in the command. The ArgumentList parameter supplies the values of the variables, in the order that they are listed.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsJob

Runs the command as a background job on a remote computer. Use this parameter to run commands that take an extensive time to complete.

When you use AsJob, the command returns an object that represents the job, and then displays the command prompt. You can continue to work in the session while the job completes. To manage the job, use the Job cmdlets. To get the job results, use Receive-Job.

The AsJob parameter is similar to using Invoke-Command to run a Start-Job command remotely. However, with AsJob, the job is created on the local computer, even though the job runs on a remote computer, and the results of the remote job are automatically returned to the local computer.

For more information about Windows PowerShell background jobs, see about_Jobs and about_Remote_Jobs.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationMechanism>

Specifies the mechanism that is used to authenticate the user's credentials. Valid values are Default, Basic, Credssp, Digest, Kerberos, Negotiate, and NegotiateWithImplicitCredential. The default value is Default.

CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows.

For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in MSDN.

CAUTION: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

Required? | false
Position? | named
Default Value | Default
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CertificateThumbprint <string>

Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate.

Certificates are used in client certificate-based authentication. They can only be mapped to local user accounts; they do not work with domain accounts.

To get a certificate thumbprint, use the Get-Item or Get-ChildItem commands in the Windows PowerShell Cert: drive.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Specifies the computers on which the command runs. The default is the local computer.

When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used only to run the specified command and is then closed. If you need a persistent connection, use the Session parameter.

Type the NETBIOS name, IP address, or fully-qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, "localhost", or a dot (.).

To use an IP address in the value of the ComputerName parameter, the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_Troubleshooting.

Note: On Windows Vista, and later versions of Windows, to include the local computer in the value of the ComputerName parameter, you must open Windows PowerShell with the "Run as administrator" option.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-ConfigurationName <string>

Specifies the session configuration that is used for the new PSSession.

Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: http://schemas.microsoft.com/powershell.

The session configuration for a session is located on the remote computer. If the specified session configuration does not exist on the remote computer, the command fails.

The default value is the value of the $PSSessionConfigurationName preference variable on the local computer. If this preference variable is not set, the default is Microsoft.PowerShell. For more information, see about_Preference_Variables.

Required? | false
Position? | named
Default Value | http://Schemas.Microsoft.com/PowerShell/Microsoft.PowerShell
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-ConnectionURI <Uri[]>

Specifies a Uniform Resource Identifier (URI) that defines the connection endpoint. The URI must be fully qualified.

The format of this string is:

<Transport>://<ComputerName>:<Port>/<ApplicationName>

The default value is:

http://localhost:80/WSMAN

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you do not specify a ConnectionURI, you can use the UseSSL, ComputerName, Port, and ApplicationName parameters to specify the URI values.

If the destination computer redirects the connection to a different URI, Windows PowerShell prevents the redirection unless you use the AllowRedirection parameter in the command.

Required? | false
Position? | 1
Default Value | http://localhost:80/wsman
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a variable that contains a PSCredential object, such as one generated by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-FilePath <string>

Runs the specified local script on one or more remote computers. Enter the path and file name of the script, or pipe a script path to Invoke-Command. The script must reside on the local computer or in a directory that the local computer can access. Use the ArgumentList parameter to specify the values of parameters in the script.

When you use this parameter, Windows PowerShell converts the contents of the specified script file to a script block, transmits the script block to the remote computer, and runs it on the remote computer.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-HideComputerName

Omits the computer name of each object from the output display. By default, the name of the computer that generated the object appears in the display.

This parameter affects only the output display. It does not change the object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies input to the command. Enter a variable that contains the objects or type a command or expression that gets the objects.

When using InputObject, use the $input automatic variable in the value of the ScriptBlock parameter to represent the input objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-JobName <string>

Specifies a friendly name for the background job. By default, jobs are named "Job<n>", where <n> is an ordinal number. This parameter is valid only with the AsJob parameter.

If you use the JobName parameter in a command, the command is run as a job, and Invoke-Command returns a job object, even if you do not include the AsJob parameter in the command.

For more information about Windows PowerShell background jobs, see about_Jobs.

Required? | false
Position? | named
Default Value | Job<n>
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Port <int>

Specifies the network port on the remote computer used for this command. The default is port 80 (the HTTP port).

Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. To configure the listener, type the following two commands at the Windows PowerShell prompt:

remove-item -path wsman:\Localhost\listener\listener* -recurse

new-item -path wsman:\Localhost\listener -Transport http -Address * -port <port-number>

Do not use the Port parameter unless you must. The Port set in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ScriptBlock <scriptblock>

Specifies the commands to run. Enclose the commands in curly braces ( { } ) to create a script block. This parameter is required.

By default, any variables in the command are evaluated on the remote computer. To include local variables in the command, use the ArgumentList parameter.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Session <PSSession[]>

Runs the command in the specified Windows PowerShell sessions (PSSessions). Enter a variable that contains the PSSessions or a command that creates or gets the PSSessions, such as a New-PSSession or Get-PSSession command.

When you create a PSSession, Windows PowerShell establishes a persistent connection to the remote computer. Use a PSSession to run a series of related commands that share data. To run a single command or a series of unrelated commands, use the ComputerName parameter.

To create a PSSession, use the New-PSSession cmdlet. For more information, see about_PSSessions.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-SessionOption <PSSessionOption>

Sets advanced options for the session. Enter a SessionOption object that you create by using the New-PSSessionOption cmdlet.

The default values for the options are determined by the value of the $PSSessionOption preference variable, if it is set. Otherwise, the session uses the system defaults.

For a description of the session options, including the default values, see the help topic for the New-PSSessionOption cmdlet. For information about the $PSSessionOption preference variable, see about_Preference_Variables.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.

The throttle limit applies only to the current command, not to the session or to the computer.

Required? | false
Position? | named
Default Value | 32
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all Windows PowerShell content transmitted over the network. UseSSL is an additional protection that sends the data across an HTTPS, instead of HTTP.

If you use this parameter, but SSL is not available on the port used for the command, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.ScriptBlock You can pipe a command in a script block to Invoke-Command. Use the $input automatic variable to represent the input objects in the command.
Outputs | System.Management.Automation.PSRemotingJob or the output of the invoked command When you use the AsJob parameter, Invoke-Command returns a job object. Otherwise, it returns the output of the invoked command (the value of the ScriptBlock parameter).

Notes

-- On Windows Vista, and later versions of Windows, to use the ComputerName parameter of Invoke-Command to run a command on the local computer, you must open Windows PowerShell with the "Run as administrator" option.

-- When you run commands on multiple computers, Windows PowerShell connects to the computers in the order in which they appear in the list. However, the command output is displayed in the order that it is received from the remote computers, which might be different.

-- Errors that result from the command that Invoke-Command runs are included in the command results. Errors that would be terminating errors in a local command are treated as non-terminating errors in a remote command. This strategy ensures that terminating errors on one computer do not terminate the command on all computers on which it is run. This practice is used even when a remote command is run on a single computer.

-- If the remote computer is not in a domain that the local computer trusts, the computer might not be able to authenticate the user's credentials. To add the remote computer to the list of "trusted hosts" in WS-Management, use the following command in the WSMAN provider, where <Remote-Computer-Name> is the name of the remote computer:

set-item -path wsman:\Localhost\Client\TrustedHosts -value <Remote-Computer-Name>.

Example 1

C:\PS>invoke-command -filepath c:\scripts\test.ps1 -computerName Server01

Disks: C:, D:, E:
Status: Warning, Normal, Normal

Description
-----------
This command runs the Test.ps1 script on the Server01 computer.

The command uses the FilePath parameter to specify a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer.

Example 2

C:\PS>invoke-command -computername server01 -credential domain01\user01 -scriptblock {get-culture}

This command runs a Get-Culture command on the Server01 remote computer.

It uses the ComputerName parameter to specify the computer name and the Credential parameter to run the command in the security context of "Domain01\User01," a user with permission to run commands. It uses the ScriptBlock parameter to specify the command to be run on the remote computer.

In response, Windows PowerShell displays a dialog box that requests the password and an authentication method for the User01 account. It then runs the command on the Server01 computer and returns the result.

Example 3

C:\PS>$s = new-pssession -computername server02 -credential domain01\user01

C:\PS> invoke-command -session $s -scriptblock {get-culture}

This example runs the same "Get-Culture" command in a session (a persistent connection) on the Server02 remote computer. Typically, you create a session only when you are running a series of commands on the remote computer.

The first command uses the New-PSSession cmdlet to create a session on the Server02 remote computer. Then, it saves the session in the $s variable.

The second command uses the Invoke-Command cmdlet to run the Get-Culture command on Server02. It uses the Session parameter to specify the session  saved in the $s variable.

In response, Windows PowerShell runs the command in the session on the Server02 computer.

Example 4

C:\PS>invoke-command -computername Server02 -scriptblock {$p = get-process powershell}

C:\PS> invoke-command -computername Server02 -scriptblock {$p.virtualmemorysize}
C:\PS>

C:\PS> $s = new-pssession -computername Server02
C:\PS> invoke-command -session $s -scriptblock {$p = get-process powershell}
C:\PS> invoke-command -session $s -scriptblock {$p.virtualmemorysize}
17930240

Description
-----------
This example compares the effects of using ComputerName and Session parameters of Invoke-Command. It shows how to use a session to run a series of commands that share the same data.

The first two commands use the ComputerName parameter of Invoke-Command to run commands on the Server02 remote computer. The first command uses the Get-Process command to get the PowerShell process on the remote computer and to save it in the $p variable. The second command gets the value of the VirtualMemorySize property of the PowerShell process.

The first command succeeds. But, the second command fails because when you use the ComputerName parameter, Windows PowerShell creates a connection just to run the command. Then, it closes the connection when the command is complete. The $p variable was created in one connection, but it does not exist in the connection created for the second command.

The problem is solved by creating a session (a persistent connection) on the remote computer and by running both of the related commands in the same session.

The third command uses the New-PSSession cmdlet to create a session on the Server02 computer. Then it saves the session in the $s variable. The fourth and fifth commands repeat the series of commands used in the first set, but in this case, the Invoke-Command command uses the Session parameter to run both of the commands in the same session.

In this case, because both commands run in the same session, the commands succeed, and the $p value remains active in the $s session for later use.

Example 5

C:\PS>$command = { get-eventlog -log "windows powershell" | where {$_.message -like "*certificate*"} }

C:\PS> invoke-command -computername S1, S2 -scriptblock $command

This example shows how to enter a command that is saved in a local variable.

When the entire command is saved in a local variable, you can specify the variable as the value of the ScriptBlock parameter. You do not have to use the "param" keyword or the ArgumentList variable to submit the value of the local variable.

The first command saves a Get-Eventlog command in the $command variable. The command is formatted as a script block.

The second command uses the Invoke-Command cmdlet to run the command in $command on the S1 and S2 remote computers.

Example 6

C:\PS>invoke-command -computername server01, server02, TST-0143, localhost -configurationname MySession.PowerShell -scriptblock {get-eventlog "windows powershell"}

This example demonstrates how to use the Invoke-Command cmdlet to run a single command on multiple computers.

The command uses the ComputerName parameter to specify the computers. The computer names are presented in a comma-separated list. The list of computers includes the "localhost" value, which represents the local computer.

The command uses the ConfigurationName parameter to specify an alternate session configuration for Windows PowerShell and the ScriptBlock parameter to specify the command.

In this example, the command in the script block gets the events in the Windows PowerShell event log on each remote computer.

Example 7

C:\PS>$version = invoke-command -computername (get-content machines.txt) -scriptblock {(get-host).version}

This command gets the version of the Windows PowerShell host running on 200 remote computers.

Because only one command is run, it is not necessary to create persistent connections (sessions) to each of the computers. Instead, the command uses the ComputerName parameter to indicate the computers.

The command uses the Invoke-Command cmdlet to run a Get-Host command. It uses dot notation to get the Version property of the Windows PowerShell host.

To specify the computers, it uses the Get-Content cmdlet to get the contents of the Machine.txt file, a file of computer names.

These commands run synchronously (one at a time). When the commands complete, the output of the commands from all of the computers is saved in the $version variable. The output includes the name of the computer from which the data originated.

Example 8

C:\PS>$s = new-pssession -computername Server01, Server02

C:\PS> invoke-command -session $s -scriptblock {get-eventlog system} -AsJob

Id   Name    State      HasMoreData   Location           Command
---  ----    -----      -----         -----------        --------             -------
1    Job1    Running    True          Server01,Server02  get-eventlog system

C:\PS> $j = Get-Job

C:\PS> $j | format-list -property *

HasMoreData   : True
StatusMessage :
Location      : Server01,Server02
Command       : get-eventlog system
JobStateInfo  : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : e124bb59-8cb2-498b-a0d2-2e07d4e030ca
Id            : 1
Name          : Job1
ChildJobs     : {Job2, Job3}
Output        : {}
Error         : {}
Progress      : {}
Verbose       : {}
Debug         : {}
Warning       : {}
StateChanged  :

C:\PS> $results = $j | Receive-Job

Description
-----------
These commands run a background job on two remote computers. Because the Invoke-Command command uses the AsJob parameter, the commands run on the remote computers, but the job actually resides on the local computer and the results are transmitted to the local computer.

The first command uses the New-PSSession cmdlet to create sessions on the Server01 and Server02 remote computers.

The second command uses the Invoke-Command cmdlet to run a background job in each of the sessions. The command uses the AsJob parameter to run the command as a background job. This command returns a job object that contains two child job objects, one for each of the jobs run on the two remote computers.

The third command uses a Get-Job command to save the job object in the $j variable.

The fourth command uses a pipeline operator (|) to send the value of the $j variable to the Format-List cmdlet, which displays all properties of the job object in a list.

The fifth command gets the results of the jobs. It pipes the job object in $j to the Receive-Job cmdlet and stores the results in the $results variable.

Example 9

C:\PS>$MWFO-LOg = Microsoft-Windows-Forwarding/Operational

invoke-command -computername server01 -scriptblock {param($log, $num) get-eventlog -logname $log -newest $num} -ArgumentList $MWFO-log, 10

This example shows how to include the values of local variables in a command run on a remote computer.

The first command saves the name of the Microsoft-Windows-Forwarding/Operational event log in the $MWFO-Log variable.

The second command uses the Invoke-Command cmdlet to run a Get-EventLog command on the Server01 remote computer that gets the 10 newest events from the Microsoft-Windows-Forwarding/Operational event log on Server01.

This command uses the "param" keyword to create two variables, $log and $num, that are used as placeholders in the Get-EventLog command. These placeholders have arbitrary names that do not need to match the names of the local variables that supply their values.

The values of the ArgumentList parameter demonstrate the two different ways to specify values in the argument list. The value of the $log placeholder is the $MFWO-Log variable, which is defined in the first command. The value of the $num variable is 10.

Before the command is sent to the remote computer, the variables are replaced with the specified values.

Example 10

C:\PS>invoke-command -computername S1, S2 -scriptblock {get-process powershell}

PSComputerName    Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id   ProcessName
--------------    -------  ------    -----      ----- -----   ------     --   -----------
S1                575      15        45100      40988   200     4.68     1392 powershell
S2                777      14        35100      30988   150     3.68     67   powershell

C:\PS> invoke-command -computername S1, S2 -scriptblock {get-process powershell} -HideComputerName

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id   ProcessName
-------  ------    -----      ----- -----   ------     --   -----------
575      15        45100      40988   200     4.68     1392 powershell
777      14        35100      30988   150     3.68     67   powershell

Description
-----------
This example shows the effect of using the HideComputerName parameter of Invoke-Command.

The first two commands use the Invoke-Command cmdlet to run a Get-Process command for the PowerShell process. The output of the first command includes the PsComputerName property, which contains the name of the computer on which the command ran. The output of the second command, which uses the HideComputerName parameter, does not include the PsComputerName column.

Using the HideComputerName parameter does not change the object. You can still use the Format cmdlets to display the PsComputerName property of any of the affected objects.

Example 11

C:\PS>invoke-command -comp (get-content servers.txt) -filepath c:\scripts\sample.ps1 -argumentlist Process, Service

This example uses the Invoke-Command cmdlet to run the Sample.ps1 script on all of the computers listed in the Servers.txt file. The command uses the FilePath parameter to specify the script file. This command allows you to run the script on the remote computers, even if the script file is not accessible to the remote computers.

When you submit the command, the content of the Sample.ps1 file is copied into a script block and the script block is run on each of the remote computers. This procedure is equivalent to using the ScriptBlock parameter to submit the contents of the script.

Example 12

C:\PS>$LiveCred = Get-Credential

C:\PS> Invoke-Command -ConfigurationName Microsoft.Exchange `
         -ConnectionUri https://ps.exchangelabs.com/powershell `
         -Credential $LiveCred  -Authentication Basic `
         -scriptblock {Invoke-Command {Set-Mailbox dan -DisplayName "Dan Park"}

This example shows how to run a command on a remote computer that is identified by a URI (Internet address). This particular example runs a Set-Mailbox command on a remote Exchange server. The backtick (`) in the command is the Windows PowerShell continuation character.

The first command uses the Get-Credential cmdlet to store Windows Live ID credentials in the $LiveCred variab the credentials dialog box appears, enter Windows Live ID credentials.

The second command uses the Invoke-Command cmdlet to run a Set-Mailbox command. The command uses the ConfigurationName parameter to specify that the command should run in a session that uses the Microsoft.Exchange session configuration. The ConnectionURI parameter specifies the URL of the Exchange server endpoint.

The credential parameter specifies tle. Whenhe Windows Live credentials stored in the $LiveCred variable. The AuthenticationMechanism parameter specifies the use of basic authentication. The ScriptBlock parameter specifies a script block that contains the command.

Example 13

C:\PS>$max = New-PSSessionOption -MaximumRedirection 1

C:\PS> Invoke-Command -ConnectionUri https://ps.exchangelabs.com/powershell `
         -scriptblock {Invoke-Command {Get-Mailbox dan} `
         -AllowRedirection -SessionOption $max

This command shows how to use the AllowRedirection and SessionOption parameters to manage URI redirection in a remote command.

The first command uses the New-PSSessionOption cmdlet to create a PSSessionOpption object that it saves in the $max variable. The command uses the MaximumRedirection parameter to set the MaximumConnectionRedirectionCount property of the PSSessionOption object to 1.

The second command uses the Invoke-Command cmdlet to run a Get-Mailbox command on a remote server running Microsoft Exchange Server. The command uses the AllowRedirection parameter to provide explicit permission to redirect the connection to an alternate endpoint. It also uses the SessionOption parameter to specify the session object in the $max variable.

As a result, if the remote computer specified by the ConnectionURI parameter returns a redirection message, Windows PowerShell will redirect the connection, but if the new destination returns another redirection message, the redirection count value of 1 is exceeded, and Invoke-Command returns a non-terminating error.

Example 14

C:\PS>$so = New-PSSessionOption -SkipCACheck

PS C:\> invoke-command $s { get-hotfix } -SessionOption $so -credential server01\user01

This example shows how to create and use a SessionOption parameter.

The first command uses the New-PSSessionOption cmdlet to create a session option. It saves the resulting SessionOption object in the $so parameter.

The second command uses the Invoke-Command cmdlet to run a Get-Hotfix command remotely. The value of the SessionOption parameter is the SessionOption object in the $so variable.

Example 15

C:\PS>C:\PS> enable-wsmanCredSSP -delegate server02

C:\PS> connect-wsman Server02

C:\PS> set-item wsman:\server02*\service\auth\credSSP -value $true

C:\PS> $s = new-pssession server02

C:\PS> invoke-command -session $s -script {get-item \\Net03\Scripts\LogFiles.ps1} -authentication credssp -credential domain01\admin01

Description
-----------
This example shows how to access a network share from within a remote session.

The command requires that CredSSP delegation be enabled in the client settings on the local computer and in the service settings on the remote computer. To run the commands in this example, you must be a member of the Administrators group on the local computer and the remote computer.

The first command uses the Enable-WSManCredSSP cmdlet to enable CredSSP delegation from the Server01 local computer to the Server02 remote computer. This configures the CredSSP client setting on the local computer.

The second command uses the Connect-WSman cmdlet to connect to the Server02 computer. This action adds a node for the Server02 computer to the WSMan: drive on the local computer, allowing you to view and change the WS-Management settings on the Server02 computer.

The third command uses the Set-Item cmdlet to change the value of the CredSSP item in the Service node of the Server02 computer to True. This action enables CredSSP in the service settings on the remote computer.

The fourth command uses the New-PSSession cmdlet to create a PSSession on the Server02 computer. It saves the PSSession in the $s variable.

The fifth command uses the Invoke-Command cmdlet to run a Get-Item command in the session in $s that gets a script from the Net03\Scripts network share. The command uses the Credential parameter and it uses the Authentication parameter with a value of CredSSP.

See Also

  • about_Remote
  • about_PSSessions
  • New-PSSession
  • Get-PSSession
  • Remove-PSSession
  • Enter-PSSession
  • Exit-PSSession
  • WS-Management Provider


Invoke-Expression

Runs commands or expressions on the local computer.

Syntax

Invoke-Expression [-Command] <string> [<CommonParameters>]

Description

The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged.

Parameters

-Command <string>

Specifies the command or expression to run. Type the command or expression or enter a variable that contains the command or expression. The Command parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String or PSObject You can pipe an object that represents the command to Invoke-Expression. Use the $input automatic variable to represent the input objects in the command.
Outputs | PSObject Returns the output that is generated by the invoked command (the value of the Command parameter).

Notes

-- An expression is a statement that can be evaluated and produces a result, such as a Windows PowerShell command.

-- Take reasonable precautions when using the Invoke-Expression cmdlet in scripts. When using Invoke-Expression to run a command that the user enters, verify that the command is safe to run before running it. In general, it is best to design your script with predefined input options, rather than allowing freeform input.

Example 1

C:\PS>$command = "Get-Process"

C:\PS> $command
Get-Process

C:\PS> invoke-expression $command

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    296       4     1572       1956    20     0.53   1348 AdtAgent
    270       6     1328        800    34     0.06   2396 alg
     67       2      620        484    20     0.22    716 ati2evxx
   1060      15    12904      11840    74    11.48    892 CcmExec
   1400      33    25280      37544   223    38.44   2564 communicator
...

Description
-----------
This example demonstrates the use of Invoke-Expression to evaluate an expression. Without Invoke-Expression, the expression is printed, but not evaluated.

The first command assigns a value of "Get-Process" (a string) to the $command variable.

The second command shows the effect of typing the variable name at the command line. Windows PowerShell echoes the string.

The third command uses Invoke-Expression to evaluate the string.

Example 2

C:\PS>invoke-expression -command "C:\ps-test\testscript.ps1"

C:\PS> "C:\ps-test\testscript.ps1" | invoke-expression

These commands use Invoke-Expression to run a script, TestScript.ps1, on the local computer. The two commands are equivalent. The first uses the Command parameter to specify the command to run. The second uses a pipeline operator (|) to send the command string to Invoke-Expression.

Example 3

C:\PS>$cmd = 'get-process | where {$_.cpu -gt 1000}'

C:\PS> iex $command

This example runs a command string that is saved in the $cmd variable.

The command string is enclosed in single quotation marks because it includes a variable, $_, which represents the current object. If it were enclosed in double quotation marks, the $_ variable would be replaced by its value before it was saved in the $command string.

Example 4

C:\PS>$cmdlet_name = "get-eventlog"

C:\PS> $example_number = 1

C:\PS> $example_code = (get-help $cmdlet_name).examples.example[($example_number-1)].code

C:\PS> invoke-expression $example_code

This command retrieves and runs the first example in the Get-EventLog cmdlet help topic.

To run an example of a different cmdlet, change the value of the $cmdlet_name variable to the name of the cmdlet. And, change the $example_number variable to the example number you want to run. The command will fail if the example number is not valid.

See Also

  • Invoke-Command


Invoke-History

Runs commands from the session history.

Syntax

Invoke-History [[-Id] <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Invoke-History cmdlet runs commands from the session history. You can pass objects representing the commands from Get-History to Invoke-History, or you can identify commands in the current history by using their ID number. To find the identification number of a command, use Get-History.

Parameters

-Id <string>

Identifies a command in the history. You can type the ID number of the command or the first few characters of the command.

If you type characters, Invoke-History matches the most recent commands first. If you omit this parameter, Invoke-History runs the last (most recent) command. The parameter name ("id") is optional. To find the ID number of a command, use Get-History.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None Invoke-History does not generate any output, but output might be generated by the commands that Invoke-History runs.

Notes

The session history is a list of the commands entered during the session along with the ID. The session history represents the order of execution, the status, and the start and end times of the command. As you enter each command, Windows PowerShell adds it to the history so that you can reuse it. For more information about the session history, see about_History.

You can also refer to Invoke-History by its built-in aliases, "r" and "ihy". For more information, see about_Aliases.

Example 1

C:\PS>invoke-history

This command runs the last (most recent) command in the session history. You can abbreviate this command as "r" (think "repeat" or "rerun"), the alias for Invoke-History.

Example 2

C:\PS>invoke-history -id 132

This command runs the command in the session history with ID 132. Because the name of the Id parameter is optional, you can abbreviate this command as "Invoke-History 132", "ihy 132", or "r 132".

Example 3

C:\PS>invoke-history get-pr

This command runs the most recent Get-Process command in the session history. When you type characters for the Id parameter, Invoke-History runs the first command that it finds that matches the pattern, beginning with the most recent commands. This command uses the ID parameter, but it omits the optional parameter name.

Example 4

C:\PS>invoke-history (16..24), 27

This command runs commands 16 through 24 and 27. You can list multiple IDs and ID ranges separated by commas.

Example 5

C:\PS>get-history -id 255 -count 7 | invoke-history

This command runs the 7 commands in the history that end with command 255 (typically 249 through 255). It uses the Get-History cmdlet to retrieve the commands. The pipeline operator (|) passes the commands to Invoke-History, which executes them.

See Also

  • about_History
  • Get-History
  • Add-History
  • Clear-History


Invoke-Item

Performs the default action on the specified item.

Syntax

Invoke-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Invoke-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Invoke-Item cmdlet performs the default action on the specified item. For example, it runs an executable file or opens a document file in the application associated with the document file type. The default action depends on the type of item and is determined by the Windows PowerShell provider that provides access to the data.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Performs the default action only on the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the item. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the selected item.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Invoke-Item.
Outputs | None The command does not generate any output. However, output might be generated by the item that it invokes.

Notes

The Invoke-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsSProvider". For more information, see about_Providers.

Example 1

C:\PS>invoke-item C:\Test\aliasApr04.doc

This command opens the file aliasApr04.doc in Microsoft Office Word. In this case, opening in Word is the default action for .doc files.

Example 2

C:\PS>invoke-item "C:\Documents and Settings\Lister\My Documents\*.xls"

This command opens all of the Microsoft Office Excel spreadsheets in the C:\Documents and Settings\Lister\My Documents folder. Each spreadsheet is opened in a new instance of Excel. In this case, opening in Excel is the default action for .xls files.

See Also

  • about_Providers
  • Clear-Item
  • Get-Item
  • Move-Item
  • Set-Item
  • New-Item
  • Remove-Item
  • Rename-Item
  • Copy-Item


Invoke-WmiMethod

Calls Windows Management Instrumentation (WMI) methods.

Syntax

Invoke-WmiMethod [-Class] <string> [[-ArgumentList] <Object[]>] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Invoke-WmiMethod [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Invoke-WmiMethod -InputObject <ManagementObject> [-ArgumentList <Object[]>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Invoke-WmiMethod -Path <string> [-ArgumentList <Object[]>] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Invoke-WmiMethod [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Invoke-WmiMethod [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Invoke-WmiMethod cmdlet calls WMI methods.

Parameters

-ArgumentList <Object[]>

Specifies the parameters to pass to the called method. The value of this parameter must be an array of objects and they must appear in the order required by the called method.

Important: A second value of $null is required, otherwise the command will generate an error, such as "Unable to cast object of type 'System.Byte' to type 'System.Array'.".

An example using an array of objects ($binSD) followed by a null value ($null) follows:

PS C:\> $acl = Get-Acl test.txt

PS C:\> $binSD = $acl.GetSecurityDescriptorBinaryForm()

PS C:\> invoke-wmimethod -class Win32_SecurityDescriptorHelper -Name BinarySDToSDDL -argumentlist $binSD, $null

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsJob

Runs the command as a background job. Use this parameter to run commands that take a long time to finish.

When you use the AsJob parameter, the command returns an object that represents the background job and then displays the command prompt. You can continue to work in the session while the job finishes. If Invoke-WmiMethod is used against a remote computer, the job is created on the local computer, and the results from remote computers are automatically returned to the local computer. To manage the job, use the cmdlets that contain the Job noun (the Job cmdlets). To get the job results, use the Receive-Job cmdlet.

Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must start Windows PowerShell by using the "Run as administrator" option in Windows Vista and later versions of Windows. For more information, see about_Remote_Requirements.

For more information about Windows PowerShell background jobs, see about_Jobs and about_Remote_Jobs.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationLevel>

Specifies the authentication level to be used with the WMI connection. Valid values are:

-1: Unchanged

0: Default

1: None (No authentication in performed.)

2: Connect (Authentication is performed only when the client establishes a relationship with the application.)

3: Call (Authentication is performed only at the beginning of each call when the application receives the request.)

4: Packet (Authentication is performed on all the data that is received from the client.)

5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.)

6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.)

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authority <string>

Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to ntlmdomain:<DomainName>, where <DomainName> identifies a valid NTLM domain name. To use Kerberos, specify kerberos:<DomainName\ServerName>. You cannot include the authority setting when you connect to the local computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Class <string>

Specifies the WMI class that contains a static method to call.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an Internet Protocol (IP) address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, a fully qualified domain name is required. You can also set the value of this parameter by piping the value to the parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or User@Contoso.com. Or, enter a PSCredential object, such as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-EnableAllPrivileges

Enables all the privileges of the current user before the command makes the WMI call.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Impersonation <ImpersonationLevel>

Specifies the impersonation level to use. Valid values are:

0: Default (Reads the local registry for the default impersonation level, which is usually set to "3: Impersonate".)

1: Anonymous (Hides the credentials of the caller.)

2: Identify (Allows objects to query the credentials of the caller.)

3: Impersonate (Allows objects to use the credentials of the caller.)

4: Delegate (Allows objects to permit other objects to use the credentials of the caller.)

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ManagementObject>

Specifies a ManagementObject object to use as input. When this parameter is used, all other parameters except the Flag and Argument parameters are ignored.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Locale <string>

Specifies the preferred locale for WMI objects. Specify the value of the Locale parameter as an array in the MS_<LCID> format in the preferred order.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies the name of the method to be invoked. This parameter is mandatory and cannot be null or empty.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Namespace <string>

When used with the Class parameter, this parameter specifies the WMI repository namespace where the referenced WMI class or object is located.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the WMI object path of a WMI class, or specifies the WMI object path of an instance of a WMI class. The class or the instance that you specify must contain the method that is specified in the Name parameter.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Allows the user to specify a throttling value for the number of WMI operations that can be executed simultaneously. This parameter is used together with the AsJob parameter. The throttle limit applies only to the current command, not to the session or to the computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>invoke-wmimethod -path win32_process -name create -argumentlist notepad.exe

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 2
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ProcessId        : 4844
ReturnValue      : 0

Description
-----------
This command starts an instance of Notepad by calling the Create method of the Win32_Process class.

Note: The ReturnValue property is populated with a 0, and the ProcessId property is populated with an integer (the next process ID number) if the command is completed.

Example 2

C:\PS>invoke-wmimethod -path "CIM_DataFile.Name='C:\scripts\test.txt'" -Name Rename -ArgumentList "C:\scripts\test_bu.txt"

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0

Description
-----------
This command renames a file. It uses the Path parameter to reference an instance of the CIM_DataFile class. Then, it applies the Rename method to that particular instance.

Note: The ReturnValue property is populated with a 0 if the command is completed.

See Also

  • Get-WmiObject
  • Remove-WmiObject
  • Set-WmiInstance
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • Remove-WSManInstance


Invoke-WSManAction

Invokes an action on the object that is specified by the Resource URI and by the selectors.

Syntax

Invoke-WSManAction [-ApplicationName <string>] [-ComputerName <string>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-UseSSL] [-ResourceURI] <Uri> [-Action] <string> [-Authentication <AuthenticationMechanism>] [-FilePath <File>] [-OptionSet <hashtable>] [-SelectorSet <hashtable>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

Invoke-WSManAction [-ConnectionURI <Uri>] [-ResourceURI] <Uri> [-Action] <string> [-Authentication <AuthenticationMechanism>] [-FilePath <File>] [-OptionSet <hashtable>] [-SelectorSet <hashtable>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

Description

The Invoke-WSManAction runs an action on the object that is specified by RESOURCE_URI, where parameters are specified by key value pairs.

This cmdlet uses the WSMan connection/transport layer to run the action.

Parameters

-Action <string>

Indicates the method to run on the management object specified by the ResourceURI and selectors.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ApplicationName <string>

Specifies the application name in the connection. The default value of the ApplicationName parameter is WSMAN. The complete identifier for the remote endpoint is in the following format:

<transport>://<server>:<port>/<ApplicationName>

For example:

http://server01:8080/WSMAN

Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency.

Required? | false
Position? | named
Default Value | wsman
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationMechanism>

Specifies the authentication mechanism to be used at the server. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.

- Default : Use the authentication method implemented by the WS-Management protocol. This is the default.

- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

- Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates.

- Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.

- CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

Caution: CredSSP delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

Required? | false
Position? | named
Default Value | localhost
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ConnectionURI <Uri>

Specifies the connection endpoint. The format of this string is:

<Transport>://<Server>:<Port>/<ApplicationName>

The following string is a properly formatted value for this parameter:

http://Server01:8080/WSMAN

The URI must be fully qualified.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or User@Domain.com. Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilePath <File>

Specifies the path of a file that is used to update a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. For example, the following command uses the FilePath parameter:

invoke-wsmanaction -action stopservice -resourceuri wmicimv2/Win32_Service -SelectorSet @{Name="spooler"} -FilePath:c:\input.xml -authentication default

This command calls the StopService method on the Spooler service by using input from a file. The file, Input.xml, contains the following content:

<p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service"/>

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OptionSet <hashtable>

Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified.

The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters:

-OptionSet @{a=1;b=2;c=3}

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Port <int>

Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server's certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted machines.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ResourceURI <Uri>

Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer.

A URI consists of a prefix and a path to a resource. For example:

http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk

http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-SelectorSet <hashtable>

Specifies a set of value pairs that are used to select particular management resource instances. The SelectorSet parameter is used when more than one instance of the resource exists. The value of the SelectorSet parameter must be a hash table.

The following example shows how to enter a value for this parameter:

-SelectorSet @{Name="WinRM";ID="yyy"}

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SessionOption <hashtable>

Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, see New-WSManSessionOption.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ValueSet <hashtable>

Specifies a hash table that helps modify a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. The value of the ValueSet parameter must be a hash table.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>invoke-wsmanaction -action startservice -resourceuri wmicimv2/win32_service  -selectorset @{name="spooler"} -authentication default

xsi         : http://www.w3.org/2001/XMLSchema-instance
p           : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
cim         : http://schemas.dmtf.org/wbem/wscim/1/common
lang        : en-US
ReturnValue : 0

Description
-----------
This command calls the StartService method of the Win32_Service WMI class instance that corresponds to the Spooler service.

The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started.

Example 2

C:\PS>invoke-wsmanaction -action stopservice -resourceuri wmicimv2/Win32_Service -SelectorSet @{Name="spooler"} -FilePath:input.xml -authentication default

xsi         : http://www.w3.org/2001/XMLSchema-instance
p           : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
cim         : http://schemas.dmtf.org/wbem/wscim/1/common
lang        : en-US
ReturnValue : 0

Description
-----------
This command calls the StopService method on the Spooler service by using input from a file. The file, Input.xml, contains the following content:

 <p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service"/>

The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started.

Example 3

C:\PS>invoke-wsmanaction -action create -resourceuri wmicimv2/win32_process -valueset @{commandline="notepad.exe";currentdirectory="C:\"}

xsi         : http://www.w3.org/2001/XMLSchema-instance
p           : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process
cim         : http://schemas.dmtf.org/wbem/wscim/1/common
lang        : en-US
ProcessId   : 6356
ReturnValue : 0

Description
-----------
This command calls the Create method of the Win32_Process class. It passes the method two parameter values, Notepad.exe and "C:\". As a result, a new process is created to run Notepad, and the current directory of the new process is set to "C:\".

Example 4

C:\PS>invoke-wsmanaction -action startservice -resourceuri wmicimv2/win32_service  -selectorset @{name="spooler"} -computername server01 -authentication default

xsi         : http://www.w3.org/2001/XMLSchema-instance
p           : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
cim         : http://schemas.dmtf.org/wbem/wscim/1/common
lang        : en-US
ReturnValue : 0

Description
-----------
This command calls the StartService method of the Win32_Service WMI class instance that corresponds to the Spooler service. Because the ComputerName parameter is specified, the command runs against the remote server01 computer.

The return value indicates whether the action was successful. In this case, a return value of 0 indicates success.  A return value of 5 indicates that the service is already started.

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan
  • Invoke-WmiMethod


Join-Path

Combines a path and a child path into a single path. The provider supplies the path delimiters.

Syntax

Join-Path [-Path] <string[]> [-ChildPath] <string> [-Credential <PSCredential>] [-Resolve] [-UseTransaction] [<CommonParameters>]

Description

The Join-Path cmdlet combines a path and child-path into a single path. The provider supplies the path delimiters.

Parameters

-ChildPath <string>

Specifies the elements to append to the value of Path. Wildcards are permitted. The ChildPath parameter is required, although the parameter name ("ChildPath") is optional.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the main path (or paths) to which the child-path is appended. Wildcards are permitted.

The value of Path determines which provider joins the paths and adds the path delimiters. The Path parameter is required, although the parameter name ("Path") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Resolve

Displays the items that are referenced by the joined path.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Join-Path.
Outputs | System.String Join-Path returns a string that contains the resulting path.

Notes

The cmdlets that contain the Path noun (the Path cmdlets) manipulate path names and return the names in a concise format that all Windows PowerShell providers can interpret. They are designed for use in programs and scripts where you want to display all or part of a path name in a particular format. Use them like you would use Dirname, Normpath, Realpath, Join, or other path manipulators.

You can use the path cmdlets with several providers, including the FileSystem, Registry, and Certificate providers.

The Join-Path cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>join-path -path c:\win* -childpath System*

This command uses Join-Path to combine the "c:\Win*" path with the "System*" child path. The Windows PowerShell file system provider, FileSystem joins the path and adds the "\" delimiter.

Example 2

C:\PS>join-path c:\win* System* -resolve

This command displays the files and folders that are referenced by joining the "c:\Win*" path and the "System*" child path. It displays the same files and folders as Get-ChildItem, but it displays the fully qualified path to each item. In this command, the Path and ChildPath optional parameter names are omitted.

Example 3

C:\PS>PS HKLM:\> join-path System *ControlSet* -resolve

This command displays the registry keys in the HKLM\System registry subkey that include "ControlSet". This example shows how to use Join-Path with the Windows PowerShell registry provider.

Example 4

C:\PS>join-path -path C:, D:, E:, F: -childpath New

This command uses Join-Path to combine multiple path roots with a child path.

Example 5

C:\PS>get-psdrive -psprovider filesystem | foreach {$_.root} | join-path -childpath Subdir

This command combines the roots of each Windows PowerShell file system drive in the console with the Subdir child path.

The command uses the Get-PSDrive cmdlet to get the Windows PowerShell drives supported by the FileSystem provider. The ForEach statement selects only the Root property of the PSDriveInfo objects and combines it with the specified child path.

The output shows that the Windows PowerShell drives on the computer included a drive mapped to the C:\Program Files directory.

See Also

  • about_Providers
  • Test-Path
  • Split-Path
  • Resolve-Path
  • Convert-Path


Limit-EventLog

Sets the event log properties that limit the size of the event log and the age of its entries.

Syntax

Limit-EventLog [-LogName] <string[]> [-ComputerName <string[]>] [-MaximumSize <Int64>] [-OverFlowAction {<OverwriteAsNeeded> | <OverwriteOlder> | <DoNotOverwrite>}] [-RetentionDays <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Limit-EventLog cmdlet sets the maximum size of a classic event log, how long each event must be retained, and what happens when the log reaches its maximum size. You can use it to limit the event logs on local or remote computers.

The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.

Parameters

-ComputerName <string[]>

Specifies a remote computer. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Limit-EventLog even if your computer is not configured to run remote commands.

Required? | false
Position? | named
Default Value | Local computer
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LogName <string[]>

Specifies the event logs. Enter the log name (the value of the Log property; not the LogDisplayName) of one or more event logs , separated by commas. Wildcard characters are not permitted. This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MaximumSize <Int64>

Specifies the maximum size of the event logs in bytes. Enter a value between 64 kilobytes (KB) and 4 gigabytes (GB). The value must be divisible by 64 KB (65536).

This parameter specifies the value of the MaximumKilobytes property of the System.Diagnostics.EventLog object that represents a classic event log.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OverFlowAction <OverflowAction>

Specifies what happens when the event log reaches its maximum size.

Valid values are:

-- DoNotOverwrite: Existing entries are retained and new entries are discarded.

-- OverwriteAsNeeded: Each new entry overwrites the oldest entry.

-- OverwriteOlder: New events overwrite events older than the value specified by the MinimumRetentionDays property. If there are no events older than specified by the MinimumRetentionDays property value, new events are discarded.

This parameter specifies the value of the OverflowAction property of the System.Diagnostics.EventLog object that represents a classic event log.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RetentionDays <int>

Specifies the minimum number of days that an event must remain in the event log.

This parameter specifies the value of the MinimumRetentionDays property of the System.Diagnostics.EventLog object that represents a classic event log.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None None
Outputs | None None

Notes

To use Limit-EventLog on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administrator" option.

Limit-EventLog changes the properties of the System.Diagnostics.EventLog object that represents a classic event log. To see the current settings of the event log properties, type "Get-EventLog -list".

Example 1

C:\PS>limit-eventLog -logname "Windows PowerShell" -MaximumSize 20KB

This command increases the maximum size of the Windows PowerShell event log on the local computer to 20480 kilobytes (KB) (20 KB).

Example 2

C:\PS>limit-eventlog -logname Security -comp Server01, Server02 -retentionDays 7

This command ensures that events in the Security log on the Server01 and Server02 computers are retained for at least 7 days.

Example 3

C:\PS>$logs = get-eventlog -list | foreach {$_.log}

C:\PS> limit-eventlog -overflowaction OverwriteOlder -logname $logs

C:\PS> get-eventlog -list

Max(K) Retain OverflowAction     Entries  Log
------ ------ --------------     -------  ---
15,168      0 OverwriteOlder       3,412  Application
   512      0 OverwriteOlder           0  DFS Replication
   512      0 OverwriteOlder          17  DxStudio
10,240      7 OverwriteOlder           0  HardwareEvents
   512      0 OverwriteOlder           0  Internet Explorer
   512      0 OverwriteOlder           0  Key Management Service
16,384      0 OverwriteOlder           4  ODiag
16,384      0 OverwriteOlder         389  OSession
                                          Security
15,168      0 OverwriteOlder      19,360  System
15,360      0 OverwriteOlder      15,828  Windows PowerShell

Description
-----------
These commands change the overflow action of all event logs on the local computer to "OverwriteOlder".

The first command gets the log names of all of the logs on the local computer. The second command sets the overflow action. The third command displays the results.

See Also

  • Clear-EventLog
  • Get-EventLog
  • Limit-EventLog
  • New-EventLog
  • Remove-EventLog
  • Show-Eventlog
  • Write-EventLog
  • Get-WinEvent


Measure-Command

Measures the time it takes to run script blocks and cmdlets.

Syntax

Measure-Command [-Expression] <scriptblock> [-InputObject <psobject>] [<CommonParameters>]

Description

The Measure-Command cmdlet runs a script block or cmdlet internally, times the execution of the operation, and returns the execution time.

Parameters

-Expression <scriptblock>

Specifies the expression that is being timed. Enclose the expression in curly braces ({}). The parameter name ("Expression") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies objects representing the expressions to be measured. Enter a variable that contains the objects or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe an object to Measure-Command.
Outputs | System.TimeSpan Measure-Command returns a time span object that represents the result.

Notes

For more information, type "Get-Help Measure-Command -detailed". For technical information, type "Get-Help Measure-Command -full".

When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>".

Example 1

C:\PS>Measure-Command { get-eventlog "windows powershell" }

This command measures the time it takes to run a "get-eventlog" command that gets the events in the Windows PowerShell event log.

Example 2

C:\PS>measure-command {get-childitem c:\windows -include *.txt -recurse}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 8
Milliseconds      : 618
Ticks             : 86182763
TotalDays         : 9.9748568287037E-05
TotalHours        : 0.00239396563888889
TotalMinutes      : 0.143637938333333
TotalSeconds      : 8.6182763
TotalMilliseconds : 8618.2763

C:\PS>measure-command {get-childitem c:\windows -filter "*.txt" -recurse}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 1
Milliseconds      : 140
Ticks             : 11409189
TotalDays         : 1.32050798611111E-05
TotalHours        : 0.000316921916666667
TotalMinutes      : 0.019015315
TotalSeconds      : 1.1409189
TotalMilliseconds : 1140.9189

Description
-----------
These commands show the value of using a provider-specific filter in Windows PowerShell commands. The first command measures the time it takes to process a recursive Get-ChildItem command that uses the Include parameter. The second command measures the time it takes to process a recursive Get-ChildItem command that uses the provider-specific Filter parameter.

See Also

  • Trace-Command
  • Invoke-Command


Measure-Object

Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text.

Syntax

Measure-Object [-Average] [-Maximum] [-Minimum] [-Sum] [[-Property] <string[]>] [-InputObject <psobject>] [<CommonParameters>]

Measure-Object [-Character] [-IgnoreWhiteSpace] [-Line] [-Word] [[-Property] <string[]>] [-InputObject <psobject>] [<CommonParameters>]

Description

The Measure-Object cmdlet calculates the property values of certain types of object. Measure-Object performs three types of measurements, depending on the parameters in the command.

The Measure-Object cmdlet performs calculations on the property values of objects. It can count objects and calculate the minimum, maximum, sum, and average of the numeric values. For text objects, it can count and calculate the number of lines, words, and characters.

Parameters

-Average

Displays the average value of the specified properties.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Character

Counts the number of characters in the input object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-IgnoreWhiteSpace

Ignores white space in word counts and character counts. By default, white space is not ignored.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be measured. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Line

Counts the number of lines in the input object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Maximum

Displays the maximum value of the specified properties.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Minimum

Displays the minimum value of the specified properties.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Property <string[]>

Specifies one or more numeric properties to measure. The default is the Count (Length) property of the object.

Required? | false
Position? | 1
Default Value | Count
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Sum

Displays the sum of the values of the specified properties.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Word

Counts the number of words in the input object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe objects to Measure-Object.
Outputs | GenericMeasureInfo or TextMeasureInfoObject

Example 1

C:\PS>get-childitem | measure-object

This command counts the files and folders in the current directory.

Example 2

C:\PS>get-childitem | measure-object -property length -minimum -maximum -average

This command displays the minimum, maximum, and sum of the sizes of all files in the current directory, and the average size of a file in the directory.

Example 3

C:\PS>get-content C:\test.txt | measure-object -character -line -word

This command displays the number of characters, words, and lines in the Text.txt file.

Example 4

C:\PS>get-process | measure-object -property workingset -minimum -maximum -average

This command displays the minimum, maximum, and average sizes of the working sets of the processes on the computer.

Example 5

C:\PS>import-csv d:\test\serviceyrs.csv | measure-object -property years -minimum -maximum -average

This command calculates the average years of service of the employees of a company.

The ServiceYrs.csv file is a CSV file that contains the employee number and years of service of each employee. The first row in the table is a header row of "EmpNo, Years".

When you use Import-Csv to import the file, the result is a PSCustomObject with note properties of EmpNo and Years. You can use Measure-Object to calculate the values of these properties, just like any other property of an object.

Example 6

C:\PS>get-childitem | measure-object -property psiscontainer -max -sum -min -average

Count    : 126
Average  : 0.0634920634920635
Sum      : 8
Maximum  : 1
Minimum  : 0
Property : PSIsContainer

Description
-----------
This example demonstrates the Measure-Object can measure Boolean values. In this case, it uses the PSIsContainer Boolean property to measure the incidence of folders (vs. files) in the current directory.

See Also

  • Compare-Object
  • ForEach-Object
  • Group-Object
  • New-Object
  • Select-Object
  • Sort-Object
  • Tee-Object
  • Where-Object


Move-Item

Moves an item from one location to another.

Syntax

Move-Item [-LiteralPath] <string[]> [[-Destination] <string>] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Move-Item [-Path] <string[]> [[-Destination] <string>] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider. For example, it can move a file or subdirectory from one directory to another or move a registry subkey from one key to another. When you move an item, it is added to the new location and deleted from its original location.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Destination <string>

Specifies the path to the location where the items are being moved. The default is the current directory. Wildcards are permitted, but the result must specify a single location.

To rename the item being moved, specify a new name in the value of the Destination parameter.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to move an item that writes over an existing read-only item. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Moves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the path to the current location of the items. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Passes an object representing the item to the pipeline. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the current location of the items. The default is the current directory. Wildcards are permitted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Move-Item.
Outputs | None or an object representing the moved item. When you use the Passthru parameter, Move-Item generates an object representing the moved item. Otherwise, this cmdlet does not generate any output.

Notes

Move-Item will move files between drives that are supported by the same provider, but it will move directories only within the same drive.

Because a Move-Item command moves the properties, contents, and child items of an item, all moves are recursive by default.

You can also refer to Move-Item by its built-in aliases, "move", "mv", and "mi". For more information, see about_Aliases.

The Move-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>move-item -path C:\test.txt -destination E:\Temp\tst.txt

This command moves the Test.txt file from the C: drive to the E:\Temp directory and renames it from "test.txt" to "tst.txt".

Example 2

C:\PS>move-item -path C:\Temp -destination C:\Logs

This command moves the C:\Temp directory and its contents to the C:\Logs directory. The Temp directory, and all of its subdirectories and files, then appear in the Logs directory.

Example 3

C:\PS>move-item -path .\*.txt -destination C:\Logs

This command moves all of the text files (*.txt) in the current directory (represented by a dot (.)) to the C:\Logs directory.

Example 4

C:\PS>get-childitem -path . -recurse -include *.txt | move-item -destination C:\TextFiles

This command moves all of the text files from the current directory and all subdirectories, recursively, to the C:\TextFiles directory.

The command uses the Get-ChildItem cmdlet to get all of the child items in the current directory (represented by the dot [.]) and its subdirectories that have a *.txt file name extension. It uses the Recurse parameter to make the retrieval recursive and the Include parameter to limit the retrieval to *.txt files.

The pipeline operator (|) sends the results of this command to Move-Item, which moves the text files to the TextFiles directory.

If files being moved to C:\Textfiles have the same name, Move-Item displays an error and continues, but it moves only one file with each name to C:\Textfiles. The other files remain in their original directories.

If the Textfiles directory (or any other element of the destination path) does not exist, the command fails. The missing directory is not created for you, even if you use the Force parameter. Move-Item moves the first item to a file called "Textfiles" and then displays an error explaining that the file already exists.

Also, by default, Get-ChildItem does not move hidden files. To move hidden files, use the Force parameter with Get-ChildItem.

Example 5

C:\PS>move-item hklm:\software\mycompany\* hklm:\software\mynewcompany

This command moves the registry keys and values within the MyCompany registry key in HKLM\Software to the MyNewCompany key. The wildcard character (*) indicates that the contents of the MyCompany key should be moved, not the key itself. In this command, the optional Path and Destination parameter names are omitted.

Example 6

C:\PS>move-item -literalpath 'Logs[Sept`06]' -destination 'Logs[2006]'

This command moves the Logs[Sept`06] directory (and its contents) into the Logs[2006] directory.

The LiteralPath parameter is used instead of Path, because the original directory name includes left bracket and right bracket characters ("[" and "]"). The path is also enclosed in single quotation marks (' '), so that the backtick symbol (`) is not misinterpreted.

The Destination parameter does not require a literal path, because the Destination variable also must be enclosed in single quotation marks, because it includes brackets that can be misinterpreted.

See Also

  • about_Providers
  • Clear-Item
  • Get-Item
  • Invoke-Item
  • Set-Item
  • New-Item
  • Remove-Item
  • Rename-Item
  • Copy-Item


Move-ItemProperty

Moves a property from one location to another.

Syntax

Move-ItemProperty [-LiteralPath] <string[]> [-Destination] <string> [-Name] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Move-ItemProperty [-Path] <string[]> [-Destination] <string> [-Name] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Move-ItemProperty cmdlet moves a property of an item from one item to another item. For example, it can move a registry entry from one registry key to another registry key. When you move an item property, it is added to the new location and deleted from its original location.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Destination <string>

Specifies the path to the destination location.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to move properties to or from items that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see about_Providers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Moves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the path to the current location of the property. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the name of the property to be moved.

Required? | true
Position? | 3
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Passes an object representing the item property. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the current location of the property. Wildcards are permitted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Move-ItemProperty.
Outputs | None or System.Management.Automation.PSCustomObject When you use the PassThru parameter, Move-ItemProperty generates a PSCustomObject representing the moved item property. Otherwise, this cmdlet does not generate any output.

Notes

The names of the Path, Destination, and Name parameters are optional. If you omit the parameter names, the unnamed parameter values must appear in this order: Path, Destination, Name. If you include the parameter names, the parameters can appear in any order.

You can also refer to Move-ItemProperty by its built-in alias, "mp". For more information, see about_Aliases.

The Move-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>move-itemproperty HKLM:\Software\MyCompany\MyApp -Name `
Version -Destination HKLM:\Software\MyCompany\NewApp

This command moves the "Version" registry value, and its data, from the MyApp subkey to the NewApp subkey of the HKLM\Software\MyCompany registry key.

See Also

  • about_Providers
  • Clear-ItemProperty
  • New-ItemProperty
  • Copy-ItemProperty
  • Rename-ItemProperty
  • Get-ItemProperty
  • Set-ItemProperty
  • Remove-ItemProperty


New-Alias

Creates a new alias.

Syntax

New-Alias [-Name] <string> [-Value] <string> [-Description <string>] [-Force] [-Option {<None> | <ReadOnly> | <Constant> | <Private> | <AllScope>}] [-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The New-Alias cmdlet creates a new alias in the current Windows PowerShell session. Aliases created by using New-Alias are not saved after you exit the session or close Windows PowerShell. You can use the Export-Alias cmdlet to save your alias information to a file. You can later use Import-Alias to retrieve that saved alias information.

Parameters

-Description <string>

Specifies a description of the alias. You can type any string. If the description includes spaces, enclose it in quotation marks.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

If set, act like Set-Alias if the alias named already exists.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies the new alias. You can use any alphanumeric characters in an alias, but the first character cannot be a number.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Option <ScopedItemOptions>

Sets one or more optional properties of the alias. Valid values are:

-- None: Sets no options. (default)

-- ReadOnly: The alias cannot be changed unless you use the Force parameter.

-- Constant: The alias cannot be changed, even by using the Force parameter.

-- Private: The alias is available only within the scope specified by the Scope parameter. It is invisible in all other scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the new alias. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Scope <string>

Specifies the scope of the new alias. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Value <string>

Specifies the name of the cmdlet or command element that is being aliased.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None or System.Management.Automation.AliasInfo When you use the Passthru parameter, New-Alias generates a System.Management.Automation.AliasInfo object representing the new alias. Otherwise, this cmdlet does not generate any output.

Notes

To create a new alias, use Set-Alias or New-Alias. To change an alias, use Set-Alias. To delete an alias, use Remove-Item.

Example 1

C:\PS>new-alias list get-childitem

This command creates an alias named "list" to represent the Get-ChildItem cmdlet.

Example 2

C:\PS>new-alias -name w -value get-wmiobject -description "quick wmi alias" -option ReadOnly

C:\PS> get-alias -name w | format-list *

This command creates an alias named "w" to represent the Get-WMIObject cmdlet. It creates a description, "quick wmi alias", for the alias and makes it read only. The last line of the command uses Get-Alias to get the new alias and pipes it to Format-List to display all of the information about it.

See Also

  • Set-Alias
  • Get-Alias
  • Export-Alias
  • Import-Alias


New-Event

Creates a new event.

Syntax

New-Event [-SourceIdentifier] <string> [[-Sender] <psobject>] [[-EventArguments] <PSObject[]>] [[-MessageData] <psobject>] [<CommonParameters>]

Description

The New-Event cmdlet creates a new custom event.

You can use custom events to notify users about state changes in your program and any change that your program can detect, including hardware or system conditions, application status, disk status, network status, or the completion of a background job.

Custom events are automatically added to the event queue in your session whenever they are raised; you do not need to subscribe to them. However, if you want to forward an event to the local session or specify an action to respond to the event, use the Register-EngineEvent cmdlet to subscribe to the custom event.

When you subscribe to a custom event, the event subscriber is added to your session. If you cancel the event subscription by using the Unregister-Event cmdlet, the event subscriber and custom event are deleted from the session. If you do not subscribe to the custom event, to delete the event, you must change the program conditions or close the Windows PowerShell session.

Parameters

-EventArguments <PSObject[]>

Specifies an object that contains options for the event.

Required? | false
Position? | 3
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MessageData <psobject>

Specifies additional data associated with the event. The value of this parameter appears in the MessageData property of the event object.

Required? | false
Position? | 4
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Sender <psobject>

Specifies the object that raises the event. The default is the Windows PowerShell engine.

Required? | false
Position? | 2
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SourceIdentifier <string>

Specifies a name for the new event. This parameter is required, and it must be unique in the session.

The value of this parameter appears in the SourceIdentifier property of the events.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.PSEventArgs

Notes

The new custom event, the event subscription, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

Example 1

C:\PS>new-event -sourceidentifier Timer -sender windows.timer  -messagedata "Test"

This command creates a new event in the Windows PowerShell event queue. It uses a Windows.Timer object to send the event.

Example 2

C:\PS>function Enable-ProcessCreationEvent
{
   $query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'"
   $processWatcher = New-Object System.Management.ManagementEventWatcher $query
   $identifier = "WMI.ProcessCreated"

   Register-ObjectEvent $processWatcher "EventArrived" -SupportEvent $identifier -Action {
       [void] (New-Event -sourceID "PowerShell.ProcessCreated" -Sender $args[0] -EventArguments $args[1].SourceEventArgs.NewEvent.TargetInstance)
   }
}

This sample function uses the New-Event cmdlet to raise an event in response to another event. The command uses the Register-ObjectEvent cmdlet to subscribe to the Windows Management Instrumentation (WMI) event that is raised when a new process is created. The command uses the Action parameter of the cmdlet to call the New-Event cmdlet, which creates the new event.

Because the events that New-Event raises are automatically added to the Windows PowerShell event queue, you do not need to register for that event.

See Also

  • Register-ObjectEvent
  • Register-EngineEvent
  • Register-WmiEvent
  • Unregister-Event
  • Get-Event
  • Remove-Event
  • Wait-Event


New-EventLog

Creates a new event log and a new event source on a local or remote computer.

Syntax

New-EventLog [-LogName] <string> [-Source] <string[]> [[-ComputerName] <string[]>] [-CategoryResourceFile <string>] [-MessageResourceFile <string>] [-ParameterResourceFile <string>] [<CommonParameters>]

Description

This cmdlet creates a new classic event log on a local or remote computer. It can also register an event source that writes to the new log or to an existing log.

The cmdlets that contain the EventLog noun (the Event log cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.

Parameters

-CategoryResourceFile <string>

Specifies the path to the file that contains category strings for the source events. This file is also known as the Category Message File.

The file must be present on the computer on which the event log is being created. This parameter does not create or move files.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Creates the new event logs on the specified computers. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-EventLog even if your computer is not configured to run remote commands.

Required? | false
Position? | 3
Default Value | .
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LogName <string>

Specifies the name of the event log.

If the log does not exist, New-EventLog creates the log and uses this value for the Log and LogDisplayName properties of the new event log. If the log exists, New-EventLog registers a new source for the event log.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MessageResourceFile <string>

Specifies the path to the file that contains message formatting strings for the source events. This file is also known as the Event Message File.

The file must be present on the computer on which the event log is being created. This parameter does not create or move files.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ParameterResourceFile <string>

Specifies the path to the file that contains strings used for parameter substitutions in event descriptions. This file is also known as the Parameter Message File.

The file must be present on the computer on which the event log is being created. This parameter does not create or move files.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Source <string[]>

Specifies the names of the event log sources, such as application programs that write to the event log. This parameter is required.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Diagnostics.EventLogEntry

Notes

To use New-EventLog on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administrator" option.

To create an event source in Windows Vista, Windows XP Professional, or Windows Server 2003, you must be a member of the Administrators group on the computer.

When you create a new event log and a new event source, the system registers the new source for the new log, but the log is not created until the first entry is written to it.

The operating system stores event logs as files. When you create a new event log, the associated file is stored in the %SystemRoot%\System32\Config directory on the specified computer. The file name is the first eight characters of the Log property with an .evt file name extension.

Example 1

C:\PS>new-eventlog -source TestApp -logname TestLog -MessageResourceFile C:\Test\TestApp.dll

This command creates the TestLog event log on the local computer and registers a new source for it.

Example 2

C:\PS>$file = "C:\Program Files\TestApps\NewTestApp.dll"

C:\PS> new-eventlog -computername Server01 -source NewTestApp -logname Application -MessageResourceFile $file -CategoryResourceFile $file

This command adds a new event source, NewTestApp, to the Application log on the Server01 remote computer.

The command requires that the NewTestApp.dll file is located on the Server01 computer.

See Also

  • Clear-EventLog
  • Get-EventLog
  • Limit-EventLog
  • New-EventLog
  • Remove-EventLog
  • Show-Eventlog
  • Write-EventLog
  • Get-WinEvent


New-Item

Creates a new item.

Syntax

New-Item [-Path] <string[]> [-Credential <PSCredential>] [-Force] [-ItemType <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

New-Item -Name <string> [[-Path] <string[]>] [-Credential <PSCredential>] [-Force] [-ItemType <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The New-Item cmdlet creates a new item and sets its value. The types of items that can be created depend upon the location of the item. For example, in the file system, New-Item is used to create files and folders. In the registry, New-Item creates registry keys and entries.

New-Item can also set the value of the items that it creates. For example, when creating a new file, New-Item can add initial content to the file.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to create an item that writes over an existing read-only item. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ItemType <string>

Specifies the provider-specified type of the new item.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string>

Specifies the name of the new item. You can use this parameter to specify the name of the new item, or include the name in the value of the Path parameter.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the location of the new item. Wildcards are permitted.

You can specify the name of the new item in the Name parameter, or include it in the Path parameter.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Value <Object>

Specifies the value of the new item. You can also pipe a value to New-Item.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Object You can pipe a value for the new item to the New-Item cmdlet.
Outputs | System.Object New-Item returns the item that it creates.

Notes

The New-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>new-item -path . -name testfile1.txt -type "file" -value "This is a text string."

This command creates a text file named testfile1.txt in the current directory. The dot (.) in the value of the Path parameter indicates the current directory. The quoted text that follows the Value parameter is added to the file as content.

Example 2

C:\PS>new-item -path c:\ -name logfiles -type directory

This command creates a directory named Logfiles in the C: drive. The Type parameter specifies that the new item is a directory, not a file or other file system object.

Example 3

C:\PS>new-item -path $profile -type file -force

This command creates a Windows PowerShell profile in the path that is specified by the $profile variable.

You can use profiles to customize Windows PowerShell. $Profile is an automatic (built-in) variable that stores the path and file name of the CurrentUser/CurrentHost profile. By default, the profile does not exist, even though Windows PowerShell stores a path and file name for it.

In this command, the $profile variable represents the path to the file. The Type parameter (or InfoType) specifies that the command creates a file. The Force parameter lets you create a file in the profile path, even when the directories in the path do not exist (Windows PowerShell creates them).

After you use this command to create a profile, you can enter aliases, functions, and scripts in the profile to customize your shell.

For more information, see about_Automatic_Variables and about_Profiles.

Example 4

C:\PS>new-item -type directory -path c:\ps-test\scripts

This command creates a new Scripts directory in the C:\PS-Test directory.

The name of the new directory item, Scripts, is included in the value of the Path parameter, instead of being specified in the value of the Name parameter. As indicated by the syntax, either command form is valid.

See Also

  • about_Providers
  • Get-Item
  • Set-Item
  • Remove-Item
  • Clear-Item
  • Invoke-Item
  • Rename-Item
  • Move-Item
  • Copy-Item


New-ItemProperty

Creates a new property for an item and sets its value. For example, you can use New-ItemProperty to create and change registry values and data, which are properties of a registry key.

Syntax

New-ItemProperty [-LiteralPath] <string[]> [-Name] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PropertyType <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

New-ItemProperty [-Path] <string[]> [-Name] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PropertyType <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The New-ItemProperty cmdlet creates a new property for a specified item and sets its value. Typically, this cmdlet is used to create new registry values, because registry values are properties of a registry key item.

This cmdlet does not add properties to an object. To add a property to an instance of an object, use the Add-Member cmdlet. To add a property to all objects of a particular type, edit the Types.ps1xml file.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter.

The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to create a property on an object that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see about_Providers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string>

Specifies a name for the new property. If the property is a registry entry, this parameter specifies the name of the entry.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the item. This parameter identifies the item to which the new property will be added.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PropertyType <string>

Specifies the type of property that will be added.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Value <Object>

Specifies the property value. If the property is a registry entry, this parameter specifies the value of the entry.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to New-ItemProperty.
Outputs | System.Management.Automation.PSCustomObject New-ItemProperty returns a custom object that contains the new property.

Notes

The New-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>new-itemproperty -path HKLM:\Software\MyCompany -name NoOfEmployees -value 822

C:\PS> get-itemproperty hklm:\software\mycompany

PSPath        : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany
PSParentPath  : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software
PSChildName   : mycompany
PSDrive       : HKLM
PSProvider    : Microsoft.PowerShell.Core\Registry
NoOfLocations : 2
NoOfEmployees : 822

Description
-----------
This command adds a new registry entry, NoOfEmployees, to the MyCompany key of the HKLM:\Software hive.

The first command uses the Path parameter to specify the path to the MyCompany registry key. It uses the Name parameter to specify a name for the entry and the Value parameter to specify its value.

The second command uses the Get-ItemProperty cmdlet to see the new registry entry.

Example 2

C:\PS>get-item -path HKLM:\Software\MyCompany | new-Itemproperty -name NoOfLocations -value 3

This command adds a new registry entry to a registry key. To specify the key, it uses a pipeline operator (|) to send an object representing the key to the New-ItemProperty cmdlet.

The first part of the command uses the Get-Item cmdlet to get the MyCompany registry key. The pipeline operator (|) sends the results of the command to the New-ItemProperty cmdlet, which adds the new registry entry, NoOfLocations, and its value, 3, to the MyCompany key.

This command works because the parameter-binding feature of Windows PowerShell associates the path of the RegistryKey object that Get-Item returns with the LiteralPath parameter of New-ItemProperty. For more information, see about_Pipelines.

See Also

  • about_Providers
  • Clear-ItemProperty
  • Copy-ItemProperty
  • Move-ItemProperty
  • Rename-ItemProperty
  • Get-ItemProperty
  • Set-ItemProperty
  • Remove-ItemProperty


New-Module

Creates a new dynamic module that exists only in memory.

Syntax

New-Module [-Name] <string> [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Function <string[]>] [-ReturnResult] [<CommonParameters>]

New-Module [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Function <string[]>] [-ReturnResult] [<CommonParameters>]

Description

The New-Module cmdlet creates a dynamic module from a script block. The members of the dynamic module, such as functions and variables, are immediately available in the session and remain available until you close the session.

Like static modules, by default, the cmdlets and functions in a dynamic module are exported and the variables and aliases are not. However, you can use the Export-ModuleMember cmdlet and the parameters of New-Module to override the defaults.

Dynamic modules exist only in memory, not on disk. Like all modules, the members of dynamic modules run in a private module scope that is a child of the global scope. Get-Module cannot get a dynamic module, but Get-Command can get the exported members.

To make a dynamic module available to Get-Module, pipe a New-Module command to Import-Module, or pipe the module object that New-Module returns to Import-Module. This action adds the dynamic module to the Get-Module list, but it does not save the module to disk or make it persistent.

Parameters

-ArgumentList <Object[]>

Specifies arguments (parameter values) that are passed to the script block.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsCustomObject

Returns a custom object with members that represent the module members.

When you use the AsCustomObject parameter, New-Module creates the dynamic module, imports the module members into the current session, and then returns a PSCustomObject object instead of a PSModuleInfo object. You can save the custom object in a variable and use dot notation to invoke the members.

If the module has multiple members with the same name, such as a function and a variable that are both named "A," only one member with each name is accessible from the custom object.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Cmdlet <string[]>

Exports only the specified cmdlets from the module into the current session. Enter a comma-separated list of cmdlets. Wildcard characters are permitted. By default, all cmdlets in the module are exported.

You cannot define cmdlets in a script block, but a dynamic module can include cmdlets if it imports the cmdlets from a binary module.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Function <string[]>

Exports only the specified functions from the module into the current session. Enter a comma-separated list of functions. Wildcard characters are permitted. By default, all functions defined in a module are exported.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Name <string>

Specifies a name for the new module. You can also pipe a module name to New-Module.

The default value is an autogenerated name that begins with "__DynamicModule_" and is followed by a GUID that specifies the path to the dynamic module.

Required? | true
Position? | 1
Default Value | "__DynamicModule_" + GUID
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-ReturnResult

Runs the script block and returns the script block results instead of returning a module object.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ScriptBlock <scriptblock>

Specifies the contents of the dynamic module. Enclose the contents in braces ( { } ) to create a script block. This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a module name string to New-Module.
Outputs | System.Management.Automation.PSModuleInfo, System.Management.Automation.PSCustomObject, or None By default, New-Module generates a PSModuleInfo object. If you use the AsCustomObject parameter, it generates a PSCustomObject object. If you use the ReturnResult parameter, it returns the result of evaluating the script block in the dynamic module.

Notes

You can also refer to New-Module by its alias, "nmo". For more information, see about_Aliases.

Example 1

C:\PS>new-module -scriptblock {function Hello {"Hello!"}}

Name              : __DynamicModule_2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5
Path              : 2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5
Description       :
Guid              : 00000000-0000-0000-0000-000000000000
Version           : 0.0
ModuleBase        :
ModuleType        : Script
PrivateData       :
AccessMode        : ReadWrite
ExportedAliases   : {}
ExportedCmdlets   : {}
ExportedFunctions : {[Hello, Hello]}
ExportedVariables : {}
NestedModules     : {}

Description
-----------
This command creates a new dynamic module with a function called "Hello". The command returns a module object that represents the new dynamic module.

Example 2

C:\PS>new-module -scriptblock {function Hello {"Hello!"}}

Name              : __DynamicModule_2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5
Path              : 2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5
Description       :
Guid              : 00000000-0000-0000-0000-000000000000
Version           : 0.0
ModuleBase        :
ModuleType        : Script
PrivateData       :
AccessMode        : ReadWrite
ExportedAliases   : {}
ExportedCmdlets   : {}
ExportedFunctions : {[Hello, Hello]}
ExportedVariables : {}
NestedModules     : {}

C:\PS> get-module
C:\PS>

C:\PS> get-command Hello

CommandType     Name   Definition
-----------     ----   ----------
Function        Hello  "Hello!"

Description
-----------
This example demonstrates that dynamic modules are not returned by the Get-Module cmdlet, but the members that they export are returned by the Get-Command cmdlet.

Example 3

C:\PS>New-Module -scriptblock {$SayHelloHelp="Type 'SayHello', a space, and a name."; function SayHello ($name) { "Hello, $name" }; Export-ModuleMember -function SayHello -Variable SayHelloHelp}

C:\PS> $SayHelloHelp
Type 'SayHello', a space, and a name.

C:\PS> SayHello Jeffrey
Hello, Jeffrey

Description
-----------
This command uses the Export-ModuleMember cmdlet to export a variable into the current session. Without the Export-ModuleMember command, only the function is exported.

The output shows that both the variable and the function were exported into the session.

Example 4

C:\PS>new-module -scriptblock {function Hello {"Hello!"}} -name GreetingModule | import-module

C:\PS> get-module

Name              : GreetingModule
Path              : d54dfdac-4531-4db2-9dec-0b4b9c57a1e5
Description       :
Guid              : 00000000-0000-0000-0000-000000000000
Version           : 0.0
ModuleBase        :
ModuleType        : Script
PrivateData       :
AccessMode        : ReadWrite
ExportedAliases   : {}
ExportedCmdlets   : {}
ExportedFunctions : {[Hello, Hello]}
ExportedVariables : {}
NestedModules     : {}

C:\PS> get-command hello

CommandType     Name                                                               Definition
-----------     ----                                                               ----------
Function        Hello                                                              "Hello!"

Description
-----------
This command demonstrates that you can make a dynamic module available to the Get-Module cmdlet by piping the dynamic module to the Import-Module cmdlet.

The first command uses a pipeline operator (|) to send the module object that New-Module generates to the Import-Module cmdlet. The command uses the Name parameter of New-Module to assign a friendly name to the module. Because Import-Module does not return any objects by default, there is no output from this command.

The second command uses the Get-Module cmdlet to get the modules in the session. The result shows that Get-Module can get the new dynamic module.

The third command uses the Get-Command cmdlet to get the Hello function that the dynamic module exports.

Example 5

C:\PS>$m = new-module -scriptblock {function Hello ($name) {"Hello, $name"}; function Goodbye ($name) {"Goodbye, $name"}} -AsCustomObject

C:\PS> $m

C:\PS> $m | get-member

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Goodbye     ScriptMethod System.Object Goodbye();
Hello       ScriptMethod System.Object Hello();

PS C:\ps-test> $m.goodbye("Jane")
Goodbye, Jane

PS C:\ps-test> $m.hello("Manoj")
Hello, Manoj

PS C:\ps-test> goodbye Jane
Goodbye, Jane

PS C:\ps-test> hello Manoj
Hello, Manoj

Description
-----------
This example shows how to use the AsCustomObject parameter of New-Module to generate a custom object with script methods that represent the exported functions.

The first command uses the New-Module cmdlet to generate a dynamic module with two functions, Hello and Goodbye. The command uses the AsCustomObject parameter to generate a custom object instead of the PSModuleInfo object that New-Module generates by default. The command saves the custom object in the $m variable.

The second command attempts to display the value of the $m variable. No content appears.

The third command uses a pipeline operator (|) to send the custom object to the Get-Member cmdlet, which displays the properties and methods of the custom object. The output shows that the object has script methods that represent the Hello and Goodbye functions.

The fourth and fifth commands use the script method format to call the Hello and Goodbye functions.

The sixth and seventh commands call the functions by specifying the function name and parameter value.

Example 6

C:\PS>new-module -scriptblock {function SayHello {"Hello, World!"}; SayHello} -returnResult

Hello, World!

Description
-----------
This command uses the ReturnResult parameter to request the results of running the script block instead of requesting a module object.

The script block in the new module defines the SayHello function and then calls the function.

See Also

  • Get-Module
  • Import-Module
  • Remove-Module
  • Export-ModuleMember
  • about_Modules


New-ModuleManifest

Creates a new module manifest.

Syntax

New-ModuleManifest [-Path] <string> -Author <string> -CompanyName <string> -Copyright <string> -Description <string> -FileList <string[]> -FormatsToProcess <string[]> -ModuleToProcess <string> -NestedModules <string[]> -RequiredAssemblies <string[]> -TypesToProcess <string[]> [-AliasesToExport <string[]>] [-ClrVersion <Version>] [-CmdletsToExport <string[]>] [-DotNetFrameworkVersion <Version>] [-FunctionsToExport <string[]>] [-Guid <Guid>] [-ModuleList <Object[]>] [-ModuleVersion <Version>] [-PassThru] [-PowerShellHostName <string>] [-PowerShellHostVersion <Version>] [-PowerShellVersion <Version>] [-PrivateData <Object>] [-ProcessorArchitecture {<None> | <MSIL> | <X86> | <IA64> | <Amd64>}] [-RequiredModules <Object[]>] [-ScriptsToProcess <string[]>] [-VariablesToExport <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The New-ModuleManifest cmdlet creates a new module manifest (.psd1) file, populates its values, and saves the manifest file in the specified path.

Module authors can use this cmdlet to create a manifest for their module. A module manifest is a .psd1 file that contains a hash table. The keys and values in the hash table describe the contents and attributes of the module, define the prerequisites, and determine how the components are processed. Manifests are not required for a module.

New-ModuleManifest creates a manifest that includes all of the commonly used manifest keys, so you can use the default output as a manifest template. To add or change values, or to add module keys that this cmdlet does not add, open the resulting file in a text editor.

Each parameter of this cmdlet (except for Path and PassThru) creates a module manifest key and its value. In a module manifest, only the ModuleVersion key is required. However, several other parameters of this cmdlet are mandatory. As a result, you can type a "New-ModuleManifest" command without parameters and the cmdlet will prompt you for values for other commonly used keys. To leave the value empty, press ENTER.

For a complete description of the format, effects, and requirements of a module manifest, see "How to Write a Module Manifest" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143613.

Parameters

-AliasesToExport <string[]>

Specifies the aliases that the module exports. Wildcards are permitted.

You can use this parameter to restrict the aliases that are exported by the module. It can remove aliases from the list of exported aliases, but it cannot add aliases to the list.

If you omit this parameter, New-ModuleManifest creates an AliasesToExport key with a value of * (all), meaning that all aliases that are exported by the module are exported by the manifest.

Required? | false
Position? | named
Default Value | * (all)
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Author <string>

Specifies the module author.

This parameter is required by the cmdlet, but the Author key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates an Author key with the name of the current user.

Required? | true
Position? | named
Default Value | Name of the current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ClrVersion <Version>

Specifies the version of the Common Language Runtime (CLR) of the Microsoft .NET Framework that the module requires.

If you omit this parameter, New-ModuleManifest creates a CLRVersion key with an empty string value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CmdletsToExport <string[]>

Specifies the cmdlets that the module exports. Wildcards are permitted.

You can use this parameter to restrict the cmdlets that are exported by the module. It can remove cmdlets from the list of exported cmdlets, but it cannot add cmdlets to the list.

If you omit this parameter, New-ModuleManifest creates a CmdletsToExport key with a value of * (all), meaning that all cmdlets that are exported by the module are exported by the manifest.

Required? | false
Position? | named
Default Value | * (all)
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-CompanyName <string>

Identifies the company or vendor who created the module.

This parameter is required by the cmdlet, but the CompanyName key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a CompanyName key with a value of "Unknown".

Required? | true
Position? | named
Default Value | "Unknown"
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Copyright <string>

Specifies a copyright statement for the module.

This parameter is required by the cmdlet, but the Copyright key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a Copyright key with a value of "(c) <year> <username>. All rights reserved." where <year> is the current year and <username> is the value of the Author key (if one is specified) or the name of the current user.

Required? | true
Position? | named
Default Value | (c) <year> <username>. All rights reserved.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Description <string>

Describes the contents of the module.

This parameter is required by the cmdlet, but the Description key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a Description key with an empty string value.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DotNetFrameworkVersion <Version>

Specifies the version of the Microsoft .NET Framework that the module requires.

If you omit this parameter, New-ModuleManifest creates a DotNetFrameWorkVersion key with an empty string value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FileList <string[]>

Specifies all items that are included in the module.

This key is designed to act as a module inventory. These files are not automatically exported with the module.

This parameter is required by the cmdlet, but the FileList key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a FileList key with an empty array value.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FormatsToProcess <string[]>

Specifies the formatting files (.ps1xml) that run when the module is imported.

When you import a module, Windows PowerShell runs the Update-FormatData cmdlet with the specified files. Because formatting files are not scoped, they affect all session states in the session.

This parameter is required by the cmdlet, but the FormatsToProcess key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a FormatsToProcess key with an empty array value.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FunctionsToExport <string[]>

Specifies the functions that the module exports. Wildcards are permitted.

You can use this parameter to restrict the functions that are exported by the module. It can remove functions from the list of exported aliases, but it cannot add functions to the list.

If you omit this parameter, New-ModuleManifest creates an FunctionsToExport key with a value of * (all), meaning that all functions that are exported by the module are exported by the manifest.

Required? | false
Position? | named
Default Value | * (all)
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Guid <Guid>

Specifies a unique identifier for the module. The GUID can be used to distinguish among modules with the same name.

If you omit this parameter, New-ModuleManifest creates a GUID key in the manifest and generates a GUID for the value.

To create a new GUID in Windows PowerShell, type "[guid]::NewGuid()".

Required? | false
Position? | named
Default Value | A GUID generated for the module
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ModuleList <Object[]>

Lists all modules that are packaged with this module.

Enter each module name as a string or enter a hash table with ModuleName and GUID keys. The hash table can also have an optional ModuleVersion key.

This key is designed to act as a module inventory. These modules are not automatically processed.

If you omit this parameter, New-ModuleManifest creates a ModuleList key in the manifest with an empty array value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ModuleToProcess <string>

Specifies the primary or "root" file of the module. When the module is imported, the members that are exported from the root module file are imported into the caller's session state. Enter the file name of one script module (.psm1) or binary module (.dll).

If a module has a manifest file and no root file has been designated in the ModuleToProcess key, the manifest becomes the primary file for the module, and the module becomes a "manifest module" (ModuleType = Manifest).

To export members from .psm1 or .dll files in a module that has a manifest, the names of those files must be specified in the values of the ModuleToProcess or NestedModules keys in the manifest. Otherwise, their members are not exported.

This parameter is required by the cmdlet, but the ModuleToProcess key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a ModuleToProcess key with an empty string value.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ModuleVersion <Version>

Specifies the version of the module.

This parameter is not required by the cmdlet, but a ModuleVersion key is required in the manifest. If you omit this parameter, New-ModuleManifest creates a ModuleVersion key with a value of "1.0".

Required? | false
Position? | named
Default Value | 1.0
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NestedModules <string[]>

Specifies script modules (.psm1) and binary modules (.dll) that are imported into the module's session state. The files in the NestedModules key run in the order in which they are listed in the value.

Typically, nested modules contain commands that the root module needs for its internal processing. By default, the commands in nested modules are exported from the module's session state into the caller's session state, but the root module can restrict the commands that it exports (for example, by using an Export-Module command).

Nested modules in the module session state are available to the root module, but they are not returned by a Get-Module command in the caller's session state.

Scripts (.ps1) that are listed in the NestedModules key are run in the module's session state, not in the caller's session state. To run a script in the caller's session state, list the script file name in the value of the ScriptsToProcess key in the manifest.

This parameter is required by the cmdlet, but the NestedModules key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a NestedModules key with an empty array value.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Writes the resulting module manifest to the console, in addition to creating a .psd1 file. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the path and file name of the new module manifest. Enter a path and file name with a .psd1 file name extension, such as "$pshome\Modules\MyModule\MyModule.psd1". This parameter is required.

If you specify the path to an existing file, New-ModuleManifest replaces the file without warning unless the file has the read-only attribute.

The manifest should be located in the module's directory, and the manifest file name should be the same as the module directory name, but with a .psd1 file name extension.

Note: You cannot use variables, such as $pshome or $home, in response to a prompt for a Path parameter value. To use a variable, include the Path parameter in the command.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PowerShellHostName <string>

Specifies the name of the Windows PowerShell host program that the module requires. Enter the name of the host program, such as "Windows PowerShell ISE Host" or "ConsoleHost". Wildcards are not permitted.

To find the name of a host program, in the program, type "$host.name".

If you omit this parameter, New-ModuleManifest creates a PowerShellHostName key with an empty string value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PowerShellHostVersion <Version>

Specifies the minimum version of the Windows PowerShell host program that works with the module. Enter a version number, such as 1.1.

If you omit this parameter, New-ModuleManifest creates a PowerShellHostName key with an empty string value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PowerShellVersion <Version>

Specifies the minimum version of Windows PowerShell that will work with this module. Enter 1.0 or 2.0. Requirements for versions greater than 2.0 are not enforced.

If you omit this parameter, New-ModuleManifest creates a PowerShellVersion key with an empty string value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PrivateData <Object>

Specifies data that is passed to the module when it is imported.

If you omit this parameter, New-ModuleManifest creates a PrivateData key with an empty string value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ProcessorArchitecture <ProcessorArchitecture>

Specifies the processor architecture that the module requires. Valid values are x86, AMD64, IA64, and None (unknown or unspecified).

If you omit this parameter, New-ModuleManifest creates a ProcessorArchitecture key with an empty string value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RequiredAssemblies <string[]>

Specifies the assembly (.dll) files that the module requires. Windows PowerShell loads the specified assemblies before updating types or formats, importing nested modules, or importing the module file that is specified in the value of the ModuleToProcess key.

Use this parameter to list all the assemblies that the module requires, including assemblies that must be loaded to update any formatting or type files that are listed in the FormatsToProcess or TypesToProcess keys, even if those assemblies are also listed as binary modules in the NestedModules key.

This parameter is required by the cmdlet, but the RequiredAssemblies key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a RequiredAssemblies key with an empty array value.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RequiredModules <Object[]>

Specifies modules that must be in the global session state. If the required modules are not in the global session state, attempts to import this module will fail.

Enter each module name as a string or enter a hash table with the ModuleName and GUID keys. The hash table can also have an optional ModuleVersion key. For more information, see the examples.

Windows PowerShell does not import required modules automatically. It verifies only that the required modules are present. However, modules can include scripts (.ps1) that import the required modules into the global session state.

If you omit this parameter, New-ModuleManifest creates a RequiredModules key with an empty array value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ScriptsToProcess <string[]>

Specifies script (.ps1) files that run in the caller's session state when the module is imported. You can use these scripts to prepare an environment, just as you might use a login script.

To specify scripts that run in the module's session state, use the NestedModules key.

If you omit this parameter, New-ModuleManifest creates a ScriptsToProcess key with an empty array value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-TypesToProcess <string[]>

Specifies the type files (.ps1xml) that run when the module is imported.

When you import the module, Windows PowerShell runs the Update-TypeData cmdlet with the specified files. Because type files are not scoped, they affect all session states in the session.

This parameter is required by the cmdlet, but the TypesToProcess key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a TypesToProcess key with an empty array value.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-VariablesToExport <string[]>

Specifies the variables that the module exports. Wildcards are permitted.

You can use this parameter to restrict the variables that are exported by the module. It can remove variables from the list of exported variables, but it cannot add variables to the list.

If you omit this parameter, New-ModuleManifest creates a VariablesToExport key with a value of * (all), meaning that all variables that are exported by the module are exported by the manifest.

Required? | false
Position? | named
Default Value | * (all)
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None or System.String By default, New-ModuleManifest does not generate any output. However, if you use the PassThru parameter, it generates a System.String object representing the module manifest..

Notes

Module manifests are usually optional. However, a module manifest is required to export an assembly that is installed in the global assembly cache.

To add or change files in the $pshome\Modules directory (%Windir%\System32\WindowsPowerShell\v1.0\Modules), start Windows PowerShell with the "Run as administrator" option.

A "session" is an instance of the Windows PowerShell execution environment. A session can have one or more session state. By default, a session has only a global session state, but each imported module has its own session state. Session states allow the commands in a module to run without affecting the global session state.

The "caller's session state" is the session state into which a module is imported. Typically, it refers to the global session state, but when a module imports nested modules, the "caller" is the module and the "caller's session state" is the module's session state.

Example 1

C:\PS>New-ModuleManifest

Path: C:\Users\User01\Documents\WindowsPowerShell\Modules\Test-Module\Test-Module.psd1
NestedModules[0]: BackgroundModule.psm1
Author: Jinghao Liu
CompanyName: Fabrikam, Inc.
Copyright: Copyright © 2009 Liu Jinghao. All rights reserved.
ModuleToProcess: TestModule.psm1
Description: Cmdlets to find common errors in scripts.
TypesToProcess[0]: TestTypes.ps1xml
FormatsToProcess[0]: TestFormat.ps1xml
RequiredAssemblies[0]: Test.dll
FileList[0]: Test-Module.psd1
FileList[1]: Test-Module.psm1
FileList[2]: BackgroundModule.psm1
FileList[3]: TestTypes.ps1xml
FileList[4]: TestFormat.ps1xml
FileList[5]: Test.dll
FileList[6]: TestIcon.ico

Description
-----------
This command creates a new module manifest. The cmdlet prompts you for the parameters that it requires, including the Path parameter, and creates a manifest file in the specified location.

The output of this command shows sample responses to the prompts. To use default values, press ENTER.

The actual prompt, and its handling of quoted and non-quoted phrases, depends on the host program in which Windows PowerShell is running.

Example 2

C:\PS>New-ModuleManifest -PowerShellVersion 1.0 -AliasesToExport JKBC, DRC, TAC

This command creates a new module manifest. The command includes parameters that the cmdlet does not require (or prompt for). You can include other manifest key values at the prompt.

Example 3

C:\PS>New-ModuleManifest -RequiredModules FileTransfer,@{ModuleName="BackgroundModule";GUID="486569a2-2784-48bf-af15-70ba837a64d0";ModuleVersion="3.5"}

This example shows how to use the string and hash table formats of the RequiredModules parameter value. Strings and hash tables can be used in the same command.

This command commands creates a module manifest for a module that requires the FileTransfer module and a (fictitious) module named "BackgroundModule".

The command uses a string format to specify the name of the FileTransfer module and the hash table format to specify the name, a GUID, and a version of the BackgroundModule.

See Also

  • Import-Module
  • Get-Module
  • New-Module
  • Remove-Module
  • Export-ModuleMember
  • Test-ModuleManifest
  • about_Modules


New-Object

Creates an instance of a Microsoft .NET Framework or COM object.

Syntax

New-Object -ComObject <string> [-Strict] [-Property <hashtable>] [<CommonParameters>]

New-Object [-TypeName] <string> [[-ArgumentList] <Object[]>] [-Property <hashtable>] [<CommonParameters>]

Description

The New-Object cmdlet creates an instance of a .NET Framework or COM object.

You can specify either the type of a .NET Framework class or a ProgID of a COM object. By default, you type the fully qualified name of a .NET Framework class and the cmdlet returns a reference to an instance of that class. To create an instance of a COM object, use the ComObject parameter and specify the ProgID of the object as its value.

Parameters

-ArgumentList <Object[]>

Specifies a list of arguments to pass to the constructor of the .NET Framework class. Separate elements in the list by using commas (,). The alias for ArgumentList is Args.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComObject <string>

Specifies the programmatic identifier (ProgID) of the COM object.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Property <hashtable>

Sets property values and invokes methods of the new object.

Enter a hash table in which the keys are the names of properties or methods and the values are property values or method arguments. New-Object creates the object and sets each property value and invokes each method in the order that they appear in the hash table.

If the new object is derived from the PSObject class, and you specify a property that does not exist on the object, New-Object adds the specified property to the object as a NoteProperty. If the object is not a PSObject, the command generates a non-terminating error.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Strict

Specifies that an error should be raised if the COM object that you attempt to create uses an interop assembly. This enables you to distinguish actual COM objects from .NET Framework objects with COM-callable wrappers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-TypeName <string>

Specifies the fully qualified name of the .NET Framework class. You cannot specify both the TypeName parameter and the ComObject parameter.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | Object New-Object returns the object that is created.

Notes

New-Object provides the most commonly-used functionality of the VBScript CreateObject function. A statement like Set objShell = CreateObject("Shell.Application") in VBScript can be translated to $objShell = new-object -comobject "Shell.Application" in Windows PowerShell.

New-Object expands upon the functionality available in the Windows Script Host environment by making it easy to work with .NET Framework objects from the command line and within scripts.

Example 1

C:\PS>new-object -typename System.Version -argumentlist "1.2.3.4"

Major  Minor  Build  Revision
-----  -----  -----  --------
1      2      3      4

Description
-----------
This command creates a System.Version object using the string "1.2.3.4" as the constructor.

Example 2

C:\PS>$ie = new-object -comobject InternetExplorer.Application -property @{navigate2="www.microsoft.com"; visible = $true}

This command creates an instance of the COM object that represents the Internet Explorer application. It uses the Property parameter to call the Navigate2 method and to set the Visible property of the object to $true to make the application visible.

This command is the equivalent of the following:

$ie = new-object -comobject InternetExplorer.Application
$ie.navigate2("www.microsoft.com")
$ie.visible = $true

Example 3

C:\PS>$a=new-object -comobject Word.Application -strict -property @{visible=$true}

New-Object : The object written to the pipeline is an instance of the type
"Microsoft.Office.Interop.Word.ApplicationClass" from the component's prima
ry interop assembly. If this type exposes different members than the IDispa
tch members, scripts written to work with this object might not work if the
 primary interop assembly is not installed.
At line:1 char:14
+ $a=New-Object  <<<< -COM Word.Application -Strict; $a.visible=$true

Description
-----------
This command demonstrates that specifying the Strict parameter causes the New-Object cmdlet to generate a non-terminating error when the COM object that is created uses an interop assembly.

Example 4

C:\PS>$objshell = new-object -comobject "Shell.Application"

C:\PS> $objshell | get-member

C:\PS> $objshell.ToggleDesktop()

The command uses the ComObject parameter to create a COM object with the "Shell.Application" ProgID. It stores the resulting object in the $objShell variable.

The second command pipes the $objShell variable to the Get-Member cmdlet, which displays the properties and methods of the COM object.

The third command calls the ToggleDesktop method of the object to minimize the open windows on your desktop.

See Also

  • Compare-Object
  • Select-Object
  • Sort-Object
  • ForEach-Object
  • Group-Object
  • Measure-Object
  • Tee-Object
  • Where-Object


New-PSDrive

Creates a Windows PowerShell drive in the current session.

Syntax

New-PSDrive [-Name] <string> [-PSProvider] <string> [-Root] <string> [-Credential <PSCredential>] [-Description <string>] [-Scope <string>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The New-PSDrive cmdlet creates a Windows PowerShell drive that is "mapped" to or associated with a location in a data store, such as a network drive, a directory on the local computer, or a registry key.

You can use the Windows PowerShell drives that you create to access data in the associated data store, just like you would do with any mapped drive. You can change locations into the drive (using "Set-Location", "cd", or "chdir") and access the contents of the drive (using "Get-Item", "Get-ChildItem", or "dir").

However, the Windows PowerShell drives are known only to Windows PowerShell. You cannot access them by using Windows Explorer, Windows Management Instrumentation (WMI), Component Object Model (COM), or the Microsoft .NET Framework, or by using tools such as Net Use.

Windows PowerShell drives exist only in the current Windows PowerShell session. To make the drive persistent, you can export the session to which you have added the drive, or you can save a New-PSDrive command in your Windows PowerShell profile.

To delete a drive that was created by New-PSDrive, use the Remove-PSDrive cmdlet.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Description <string>

Specifies a brief text description of the drive. Type any string.

To see the descriptions of all of the Windows PowerShell drives on your system, type "Get-PSDrive | format name, description". To see the description of a particular Windows PowerShell drives, type "(get-psdrive <DriveName>).description".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string>

Specifies a name for the new drive. You can use any valid string for the name. You are not limited to drive letters. Windows PowerShell drives names are case-sensitive.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PSProvider <string>

Specifies the Windows PowerShell provider that supports drives of this type.

For example, if the Windows PowerShell drives is associated with a network share or file system directory, the Windows PowerShell provider is "FileSystem". If the Windows PowerShell drive is associated with a registry key, the provider is "Registry".

To see a list of the providers in your Windows PowerShell session, type "Get-PSProvider".

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Root <string>

Specifies the data store location that the Windows PowerShell drive is mapped to.

For example, specify a network share (such as \\Server01\Public), a local directory (such as C:\Program Files), or a registry key (such as HKLM:\Software\Microsoft).

Required? | true
Position? | 3
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Scope <string>

Specifies a scope for the drive. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.PSDriveInfo

Notes

The New-PSDrive cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>new-psdrive -name P -psprovider FileSystem -root \\Server01\Public

Name       Provider      Root
----       --------      ----
P          FileSystem    \\Server01\Public

Description
-----------
This command creates a Windows PowerShell drive that functions like a mapped network drive in Windows. The command creates a Windows PowerShell drive named P: that is mapped to the \\Server01\Public network share.

It uses the Name parameter to specify a name for the drive, the PSProvider parameter to specify the Windows PowerShell FileSystem provider, and the Root parameter to specify the network share.

When the command completes, the contents of the \\Server01\Public share appear in the P: drive. To see them, type: "dir p:".

Example 2

C:\PS>new-psdrive -name MyDocs -psprovider FileSystem -root "C:\Documents and Settings\User01\My Documents" -Description "Maps to my My Documents folder."

Name       Provider      Root
----       --------      ----
MyDocs     FileSystem    C:\Documents and Settings\User01\My Documents

Description
-----------
This command creates a Windows PowerShell drive that provides quick access to a local directory. It creates a drive named MyDocs: that is mapped to the
"C:\Documents and Settings\User01\My Documents" directory on the local computer.

It uses the Name parameter to specify a name for the drive, the PSProvider parameter to specify the Windows PowerShell FileSystem provider, the Root parameter to specify the path to the My Documents folder, and the Description parameter to create a description of the drive.

When the command completes, the contents of the My Documents folder appear in the MyDocs: drive. To see them, type: "dir mydocs:".

Example 3

C:\PS>new-psdrive -name MyCompany -psprovider Registry -root HKLM:\Software\MyCompany

Name       Provider      Root
----       --------      ----
MyCompany  Registry      HKEY_LOCAL_MACHINE\Software\MyCo...

Description
-----------
This command creates a Windows PowerShell drive that provides quick access to a frequently checked registry key. It creates a drive named MyCompany that is mapped to the HKLM\Software\MyCompany registry key.

It uses the Name parameter to specify a name for the drive, the PSProvider parameter to specify the Windows PowerShell Registry provider, and the Root parameter to specify the registry key.

When the command completes, the contents of the MyCompany key appear in the MyCompany: drive. To see them, type: "dir MyCompany:".

Example 4

C:\PS>new-psdrive -name PsDrive -psprovider FileSystem -root \\Server01\Public

C:\PS> $drive = new-object -com wscript.network
C:\PS> $drive.MapNetworkDrive("X:", "\\Server01\Public")

C PS:\> get-psdrive public, x

Name       Provider      Root
----       --------      ----
PsDrive    FileSystem    \\Server01\public
X          FileSystem    X:\

C:\PS>get-psdrive psdrive, x | get-member

   TypeName: System.Management.Automation.PSDriveInfo
Name                MemberType Definition
----                ---------- ----------
CompareTo           Method     System.Int32 CompareTo(PSDriveInfo drive),
Equals              Method     System.Boolean Equals(Object obj),
GetHashCode         Method     System.Int32 GetHashCode()
...

C:\PS> net use
Status       Local     Remote                    Network
---------------------------------------------------------------------------
             X:        \\server01\public         Microsoft Windows Network

C:\PS> get-wmiobject win32_logicaldisk | ft deviceid
deviceid
--------
C:
D:
X:

C:\PS> get-wmiobject win32_networkconnection
LocalName                     RemoteName                    ConnectionState               Status
---------                     ----------                    ---------------               ------
X:                            \\products\public             Disconnected                  Unavailable

Description
-----------
This example shows the difference between a Windows drive that is mapped to a network share and a Windows PowerShell drive that is mapped to the same network share.

The first command uses the New-PSDrive cmdlet to create a Windows PowerShell drive called PSDrive: that is mapped to the \\Server01\Public network share.

The second set of commands uses the New-Object cmdlet to create a Wscript.Network COM object and then use its MapNetworkDrive method to map the \\Server01\Public network share to the X: drive on the local computer.

Now, you can examine the two drives. Using a Get-PSDrive drive command, the drives appear to be the same, although the network share name appears only in the root of the PSDrive: drive.

Sending the drive objects to Get-Member shows that they have the same object type, System.Management.Automation.PSDriveInfo.

However, a "net use" command, a Get-WmiObject command to the Win32_LogicalDisk class, and a Get-WmiObject command to the Win32_NetworkConnection class find only the X: drive that was created by using the Wscript.Network object. That is because Windows PowerShell drives are known only to Windows PowerShell.

If you close the Windows PowerShell session and then open a new one, the PSDrive: drive is gone, and the X: drive persists.

Therefore, when deciding which method to use to map network drives, consider how you will use the drive, whether it needs to be persistant, and whether the drive needs to be visible to other Windows features.

See Also

  • about_Providers
  • Get-PSDrive
  • Remove-PSDrive


New-PSSession

Creates a persistent connection to a local or remote computer.

Syntax

New-PSSession [[-ComputerName] <string[]>] [-ApplicationName <string>] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-Name <string[]>] [-Port <int>] [-SessionOption <PSSessionOption>] [-UseSSL] [-ThrottleLimit <int>] [<CommonParameters>]

New-PSSession [[-Session] <PSSession[]>] [-Name <string[]>] [-ThrottleLimit <int>] [<CommonParameters>]

New-PSSession [-ConnectionURI] <Uri[]> [-AllowRedirection] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-Name <string[]>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [<CommonParameters>]

Description

The New-PSSession cmdlet creates a Windows PowerShell session (PSSession) on a local or remote computer. When you create a PSSession, Windows PowerShell establishes a persistent connection to the remote computer.

Use a PSSession to run multiple commands that share data, such as a function or the value of a variable. To run commands in a PSSession, use the Invoke-Command cmdlet. To use the PSSession to interact directly with a remote computer, use the Enter-PSSession cmdlet. For more information, see about_PSSessions.

You can run commands on a remote computer without creating a PSSession by using the ComputerName parameters of Enter-PSSession or Invoke-Command. When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used for the interactive session or for a single command and is then closed.

Parameters

-AllowRedirection

Allows redirection of this connection to an alternate Uniform Resource Identifier (URI).

When you use the ConnectionURI parameter, the remote destination can return an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use the AllowRedirection parameter to allow it to redirect the connection.

You can also limit the number of times that the connection is redirected by setting the MaximumConnectionRedirectionCount property of the $PSSessionOption preference variable, or the MaximumConnectionRedirectionCount property of the value of the SessionOption parameter.

The default value is 5. For more information, see the description of the SessionOption parameter, and see New-PSSessionOption.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ApplicationName <string>

Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the ConnectionURI parameter in the command.

The default value is the value of the $PSSessionApplicationName preference variable on the local computer. If this preference variable is not defined, the default value is "WSMAN". This value is appropriate for most uses. For more information, see about_Preference_Variables.

The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the URLPrefix property of a listener on the remote computer.

Required? | false
Position? | named
Default Value | WSMAN
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Authentication <AuthenticationMechanism>

Specifies the mechanism that is used to authenticate the user's credentials. Valid values are "Default", "Basic", "Credssp", "Digest", "Kerberos", "Negotiate", and "NegotiateWithImplicitCredential". The default value is "Default".

CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows.

For more information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkID=144382.

Caution: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

Required? | false
Position? | named
Default Value | Default
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CertificateThumbprint <string>

Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate.

Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts.

To get a certificate thumbprint, use the Get-Item or Get-ChildItem command in the Windows PowerShell Cert: drive.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Creates a persistent connection (PSSession) to the specified computer. If you enter multiple computer names, New-PSSession creates multiple PSSessions, one for each computer. The default is the local computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more remote computers. To specify the local computer, type the computer name, "localhost", or a dot (.). When the computer is in a different domain than the user, the fully qualified domain name is required. You can also pipe a computer name (in quotes) to New-PSSession.

To use an IP address in the value of the ComputerName parameter, the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_Troubleshooting.

Note: In Windows Vista and later versions of Windows, to include the local computer in the value of the ComputerName parameter, you must start Windows PowerShell with the "Run as administrator" option.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-ConfigurationName <string>

Specifies the session configuration that is used for the new PSSession.

Enter a configuration name or the fully qualified resource Uniform Resource Identifier (URI) for a session configuration. If you specify only the configuration name, the following schema URI is prepended: http://schemas.microsoft.com/powershell.

The session configuration for a session is located on the remote computer. If the specified session configuration does not exist on the remote computer, the command fails.

The default value is the value of the $PSSessionConfigurationName preference variable on the local computer. If this preference variable is not set, the default is Microsoft.PowerShell. For more information, see about_Preference_Variables.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-ConnectionURI <Uri[]>

Specifies a Uniform Resource Identifier (URI) that defines the connection endpoint. The URI must be fully qualified.

The format of this string is as follows:

<Transport>://<ComputerName>:<Port>/<ApplicationName>

The default value is as follows:

http://localhost:80/WSMAN

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you do not specify a ConnectionURI, you can use the UseSSL, ComputerName, Port, and ApplicationName parameters to specify the URI values.

If the destination computer redirects the connection to a different URI, Windows PowerShell prevents the redirection unless you use the AllowRedirection parameter in the command.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01", "Domain01\User01", or "User@Domain.com", or enter a PSCredential object, such as one returned by the Get-Credential cmdlet.

When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies a friendly name for the PSSession.

You can use the name to refer to the PSSession when using other cmdlets, such as Get-PSSession and Enter-PSSession. The name is not required to be unique to the computer or the current session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Port <int>

Specifies the network port on the remote computer that is used for this command. The default is port 80 (the HTTP port).

Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. Use the following commands to configure the listener:

1. winrm delete winrm/config/listener?Address=*+Transport=HTTP

2. winrm create winrm/config/listener?Address=*+Transport=HTTP @{Port=&quot;&lt;port-number&gt;&quot;}

Do not use the Port parameter unless you must. The port setting in the command applies to all computers and sessions in which the command runs. An alternate port setting might prevent the command from running on all computers.

Required? | false
Position? | named
Default Value | 80
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Session <PSSession[]>

Uses the specified PSSession as a model for the new PSSession. This parameter creates new PSSessions with the same properties as the specified PSSessions.

Enter a variable that contains the PSSessions or a command that creates or gets the PSSessions, such as a New-PSSession or Get-PSSession command.

The resulting PSSessions have the same computer name, application name, connection URI, port, configuration name, throttle limit, and Secure Sockets Layer (SSL) value as the originals, but they have a different display name, ID, and instance ID (GUID).

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-SessionOption <PSSessionOption>

Sets advanced options for the session. Enter a SessionOption object that you create by using the New-PSSessionOption cmdlet.

The default values for the options are determined by the value of the $PSSessionOption preference variable, if it is set. Otherwise, the session uses the system defaults.

For a description of the session options, including the default values, see New-PSSessionOption. For information about the $PSSessionOption preference variable, see about_Preference_Variables.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0 (zero), the default value, 32, is used.

The throttle limit applies only to the current command, not to the session or to the computer.

Required? | false
Position? | named
Default Value | 32
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all Windows PowerShell content transmitted over the network. UseSSL is an additional protection that sends the data across an HTTPS connection instead of an HTTP connection.

If you use this parameter, but SSL is not available on the port used for the command, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String, System.URI, System.Management.Automation.Runspaces.PSSession You can pipe a ComputerName (string), ConnectionURI (URI), or Session (PSSession) object to New-PSSession.
Outputs | System.Management.Automation.Runspaces.PSSession

Notes

This cmdlet uses the Windows PowerShell remoting infrastructure. To use this cmdlet, the local computer and any remote computers must be configured for Windows PowerShell remoting. For more information, see about_Remote_Requirements.

In Windows Vista and later versions of Windows, to create a PSSession on the local computer, you must start Windows PowerShell with the "Run as administrator" option.

When you are finished with the PSSession, use the Remove-PSSession cmdlet to delete the PSSession and release its resources.

Example 1

C:\PS>$s = new-pssession

This command creates a new PSSession on the local computer and saves the PSSession in the $s variable.

You can now use this PSSession to run commands on the local computer.

Example 2

C:\PS>$Server01 = new-pssession -ComputerName Server01

This command creates a new PSSession on the Server01 computer and saves it in the $Server01 variable.

When creating multiple PSSessions, assign them to variables with useful names. This will help you manage the PSSessions in subsequent commands.

Example 3

C:\PS>$s1, $s2, $s3 = new-session -computername server1,server2,server3

This command creates three new PSSessions, one on each of the computers specified by the ComputerName parameter.

The command uses the assignment operator (=) to assign the new PSSessions to an array of variables: $s1, $s2, $s3. It assigns the Server01 PSSession to $s1, the Server02 PSSession to $s2, and the Server03 PSSession to $s3.

When you assign multiple objects to an array of variables, Windows PowerShell assigns each object to a variable in the array respectively. If there are more objects than variables, all remaining objects are assigned to the last variable. If there are more variables than objects, the remaining variables are empty (null).

Example 4

C:\PS>new-pssession -computername Server01 -port 8081 -useSSL -ConfigurationName E12

This command creates a new PSSession on the Server01 computer that connects to server port 8081 and uses the SSL protocol. The new PSSession uses an alternate session configuration called "E12".

Before setting the port, you must configure the WinRM listener on the remote computer to listen on port 8081. For more information, see the description of the Port parameter.

Example 5

C:\PS>new-pssession -session $s -credential domain01\user01

This command creates a new PSSession with the same properties as an existing PSSession. You can use this command format when the resources of an existing PSSession are exhausted and a new PSSession is needed to offload some of the demand.

The command uses the Session parameter of New-PSSession to specify the PSSession saved in the $s variable. It uses the credentials of the Domain1\Admin01 user to complete the command.

Example 6

C:\PS>$global:s = new-pssession -computername server1.domain44.corpnet.fabrikam.com -credential domain01\admin01

This example shows how to create a PSSession with a global scope on a computer in a different domain.

By default, PSSessions created at the command line are created with local scope and PSSessions created in a script have script scope.

To create a PSSession with global scope, create a new PSSession and then store the PSSession in a variable that is cast to a global scope. In this case, the $s variable is cast to a global scope.

The command uses the ComputerName parameter to specify the remote computer. Because the computer is in a different domain than the user account, the full name of the computer is specified along with the credentials of the user.

Example 7

C:\PS>$rs = get-content c:\test\servers.txt | new-PSsession -throttleLimit 50

This command creates a PSSession on each of the 200 computers listed in the Servers.txt file and it stores the resulting PSSession in the $rs variable. The PSSessions have a throttle limit of 50.

You can use this command format when the names of computers are stored in a database, spreadsheet, text file, or other text-convertible format.

Example 8

C:\PS>$s = new-PSSession -URI http://Server01:91/NewSession -credential domain01\user01

This command creates a PSSession on the Server01 computer and stores it in the $s variable. It uses the URI parameter to specify the transport protocol, the remote computer, the port, and an alternate session configuration. It also uses the Credential parameter to specify a user account with permission to create a session on the remote computer.

Example 9

C:\PS>$s = new-PSSession -computername (import-csv servers.csv) -credential domain01\admin01 -throttlelimit 16

C:\PS> invoke-command -session $s -scriptblock {get-process powershell} -AsJob

These commands create a set of PSSessions and then run a background job in each of the PSSessions.

The first command creates a new PSSession on each of the computers listed in the Servers.csv file. It uses the New-PSSession cmdlet to create the PSSession. The value of the ComputerName parameter is a command that uses the Import-Csv cmdlet to import the Servers.csv file and read its contents.

The command uses the Credential parameter to create the PSSessions with the permission of a domain administrator, and it uses the ThrottleLimit parameter to limit the command to 16 concurrent connections. The command saves the PSSessions in the $s variable.

The second command uses the AsJob parameter of Invoke-Command to start a background job that runs a "Get-Process PowerShell" command in each of the PSSessions in $s.

For more information about background jobs, see about_Jobs and about_Remote_Jobs.

Example 10

C:\PS>new-PSSession -ConnectionURI https://management.exchangelabs.com/Management

This command creates a new PSSession that connects to a computer that is specified by a URI instead of a computer name.

Example 11

C:\PS>$so = New-WSManSessionOption -SkipCACheck

PS C:\> new-pssession -ConnectionUri https://management.exchangelabs.com/Management -SessionOption $so -credential server01\admin01

This example shows how to create and use a SessionOption parameter.

The first command uses the New-WSManSessionOption cmdlet to create a session option. It saves the resulting SessionOption object in the $so parameter.

The second command uses the option in a new session. The command uses the New-PSSession cmdlet to create a new session. The value of the SessionOption parameter is the SessionOption object in the $so variable.

See Also

  • about_PSSessions
  • about_Remote
  • Get-PSSession
  • Remove-PSSession
  • Enter-PSSession
  • Exit-PSSession
  • Invoke-Command


New-PSSessionOption

Creates an object that contains advanced options for a PSSession.

Syntax

New-PSSessionOption [-ApplicationArguments <PSPrimitiveDictionary>] [-CancelTimeOut <int>] [-Culture <CultureInfo>] [-IdleTimeOut <int>] [-MaximumReceivedDataSizePerCommand <int>] [-MaximumReceivedObjectSize <int>] [-MaximumRedirection <int>] [-NoCompression] [-NoEncryption] [-NoMachineProfile] [-OpenTimeOut <int>] [-OperationTimeOut <int>] [-ProxyAccessType {<None> | <IEConfig> | <WinHttpConfig> | <AutoDetect> | <NoProxyServer>}] [-ProxyAuthentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-ProxyCredential <PSCredential>] [-SkipCACheck] [-SkipCNCheck] [-SkipRevocationCheck] [-UICulture <CultureInfo>] [-UseUTF16] [<CommonParameters>]

Description

The New-PSSessionOption cmdlet creates an object that contains advanced options for a PSSession. You can use the object as the value of the SessionOption parameter of cmdlets that create a PSSession, such as New-PSSession, Enter-PSSession, and Invoke-Command.

Without parameters, New-PSSessionOption generates an object that contains the default values for all of the options. Because all of the properties can be edited, you can use the resulting object as a template, and create standard option objects for your enterprise.

Parameters

-ApplicationArguments <PSPrimitiveDictionary>

Specifies a hash table that is sent directly to the session configuration without interpretation. This hash table is available to the session configuration as a property of the PSSenderInfo class.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CancelTimeOut <int>

Determines how long Windows PowerShell waits for a cancel operation (CTRL + C) to complete before terminating it. Enter a value in milliseconds.

The default value is 60000 (one minute). A value of 0 (zero) means no timeout; the command continues indefinitely.

Required? | false
Position? | named
Default Value | 60000
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Culture <CultureInfo>

Specifies the culture to use for the PSSession. Enter a culture name in <languagecode2>-<country/regioncode2> format, such as "ja-jP", a variable that contains a CultureInfo object, or a command that gets a CultureInfo object, such as "Get-Culture".

The default value is $null, and the culture that is set in the operating system when the PSSession is created is used in the PSSession.

Required? | false
Position? | named
Default Value | Current culture
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-IdleTimeOut <int>

Determines how long the PSSession stays open if the remote computer does not receive any communication from the local computer, including the heartbeat signal. When the interval expires, the PSSession closes.

Enter a value in milliseconds. The default value is 240000 (4 minutes). The minimum value is 60000 (1 minute).

If both the local and remote computers specify an idle timeout value, the PSSession uses the shorter timeout value. The local computer can set an idle timeout value by using this parameter or by setting an idle timeout in the $PSSessionOption preference variable. The remote computer can specify an idle timeout value in the WS-Management configuration (WSMAN:\localhost\shell\idletimeout).

Required? | false
Position? | named
Default Value | 240000
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MaximumReceivedDataSizePerCommand <int>

Specifies the maximum number of bytes that the local computer can receive from the remote computer in a single command. Enter a value in bytes. By default, there is no data size limit.

This option is designed to protect the resources on the client computer.

Required? | false
Position? | named
Default Value | No limit
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MaximumReceivedObjectSize <int>

Specifies the maximum size of an object that the local computer can receive from the remote computer. Enter a value in bytes. By default, there is no data size limit.

This option is designed to protect the resources on the client computer.

Required? | false
Position? | named
Default Value | No limit
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MaximumRedirection <int>

Determines how many times Windows PowerShell redirects a connection to an alternate Uniform Resource Identifier (URI) before the connection fails. The default value is 5. A value of 0 (zero) prevents all redirection.

This option is used in the PSSession only when the AllowRedirection parameter is used in the command that creates the PSSession.

Required? | false
Position? | named
Default Value | 5
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoCompression

Turns off packet compression in the PSSession. Compression uses more processor cycles, but it makes transmission faster.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoEncryption

Turns off data encryption.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoMachineProfile

Prevents loading the user's Windows user profile. As a result, the PSSession might be created faster, but user-specific registry settings, items such as environment variables, and certificates are not available in the PSSession.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OpenTimeOut <int>

Determines how long the client computer waits for the session connection to be established. When the interval expires, the command to establish the connection fails. Enter a value in milliseconds.

The default value is 180000 (3 minutes). A value of 0 (zero) means no time-out; the command continues indefinitely.

Required? | false
Position? | named
Default Value | 180000
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OperationTimeOut <int>

Determines the maximum time that any operation in the PSSession can run. When the interval expires, the operation fails. Enter a value in milliseconds.

The default value is 180000 (3 minutes). A value of 0 (zero) means no time-out; the operation continues indefinitely.

Required? | false
Position? | named
Default Value | 180000
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ProxyAccessType <ProxyAccessType>

Determines which mechanism is used to resolve the host name. Valid values are IEConfig, WinHttpConfig, AutoDetect, NoProxyServer and None. The default value is None.

For information about the values of this parameter, see the description of the System.Management.Automation.Remoting.ProxyAccessType enumeration in the MSDN (Microsoft Developer Network) Library at http://go.microsoft.com/fwlink/?LinkId=144756.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ProxyAuthentication <AuthenticationMechanism>

Specifies the authentication method that is used for proxy resolution. Valid values are Basic, Digest, and Negotiate. The default value is Negotiate.

For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in the MSDN library at http://go.microsoft.com/fwlink/?LinkID=144382.

Required? | false
Position? | named
Default Value | Negotiate
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ProxyCredential <PSCredential>

Specifies the credentials to use for proxy authentication. Enter a variable that contains a PSCredential object or a command that gets a PSCredential object, such as Get-Credential. If this option is not set, no credentials are specified.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SkipCACheck

Specifies that when connecting over HTTPS, the client does not validate that the server certificate is signed by a trusted certificate authority (CA).

Use this option only when the remote computer is trusted by using another mechanism, such as when the remote computer is part of a network that is physically secure and isolated, or the remote computer is listed as a trusted host in a WinRM configuration.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SkipCNCheck

Specifies that the certificate common name (CN) of the server does not need to match the hostname of the server. This option is used only in remote operations that use the HTTPS protocol.

Use this option only for trusted computers.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SkipRevocationCheck

Does not validate the revocation status of the server certificate.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UICulture <CultureInfo>

Specifies the UI culture to use for the PSSession.

Enter a culture name in <languagecode2>-<country/regioncode2> format, such as "ja-jP", a variable that contains a CultureInfo object, or a command that gets a CultureInfo object, such as Get-Culture.

The default value is $null, and the UI culture that is set in the operating system when the PSSession is created is used in the PSSession.

Required? | false
Position? | named
Default Value | Current UI culture
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseUTF16

Encode the request in UTF16 format rather than UTF8 format.

Required? | false
Position? | named
Default Value | False (UTF8 encoding)
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Management.Automation.Remoting.PSSessionOption

Notes

If the SessionOption parameter is not used in a command to create a PSSession, the session options are determined by the property values of the $PSSessionOption preference variable, if it is set. For more information about the $PSSessionOption variable, see about_Preference_Variables.

Example 1

C:\PS>New-PSSessionOption

MaximumConnectionRedirectionCount : 5
NoCompression                     : False
NoMachineProfile                  : False
ProxyAccessType                   : IEConfig
ProxyAuthentication               : Negotiate
ProxyCredential                   :
SkipCACheck                       : False
SkipCNCheck                       : False
SkipRevocationCheck               : False
OperationTimeout                  : 00:03:00
NoEncryption                      : False
UseUTF16                          : False
Culture                           :
UICulture                         :
MaximumReceivedDataSizePerCommand :
MaximumReceivedObjectSize         :
ApplicationArguments              :
OpenTimeout                       : 00:03:00
CancelTimeout                     : 00:01:00
IdleTimeout                       : 00:04:00

Description
-----------
This command creates a session option object with all of the default values.

Example 2

C:\PS>$pso = new-pssessionoption -Culture "fr-fr" -MaximumReceivedObjectSize 10MB

C:\PS> new-pssession -computerName Server01 -SessionOption $pso

Description
-----------
This example shows how to use a session option object to configure a session.

The first command creates a new session option object and saves it in the value of the $pso variable.

The second command uses the New-PSSession cmdlet to create a PSSession on the Server01 remote computer. The command uses the session option object in the value of the $pso variable as the value of the SessionOption parameter of the command.

Example 3

C:\PS>enter-pssession -computername Server01 -sessionOption (new-pssessionoption -noEncryption -noCompression)

This command uses the Enter-PSSession cmdlet to start an interactive session with the Server01 computer. The value of the SessionOption parameter is a New-PSSessionOption command with the NoEncryption and NoCompression switch parameters.

The New-PSSessionOption command is enclosed in parentheses to make sure that it runs before the Enter-PSSession command.

Example 4

C:\PS>$a = new-pssessionoption

MaximumConnectionRedirectionCount : 5
NoCompression                     : False
NoMachineProfile                  : False
ProxyAccessType                   : IEConfig
ProxyAuthentication               : Negotiate
ProxyCredential                   :
SkipCACheck                       : False
SkipCNCheck                       : False
SkipRevocationCheck               : False
OperationTimeout                  : 00:03:00
NoEncryption                      : False
UseUTF16                          : False
Culture                           :
UICulture                         :
MaximumReceivedDataSizePerCommand :
MaximumReceivedObjectSize         :
ApplicationArguments              :
OpenTimeout                       : 00:03:00
CancelTimeout                     : 00:01:00
IdleTimeout                       : 00:04:00

C:\PS> $a.UICulture = (get-UICulture)
C:\PS> $a.OpenTimeout = (new-timespan -minutes 4)
C:\PS> $a.MaximumConnectionRedirectionCount = 1

C:\PS> $a

MaximumConnectionRedirectionCount : 1
NoCompression                     : False
NoMachineProfile                  : False
ProxyAccessType                   : IEConfig
ProxyAuthentication               : Negotiate
ProxyCredential                   :
SkipCACheck                       : False
SkipCNCheck                       : False
SkipRevocationCheck               : False
OperationTimeout                  : 00:03:00
NoEncryption                      : False
UseUTF16                          : False
Culture                           :
UICulture                         : en-US
MaximumReceivedDataSizePerCommand :
MaximumReceivedObjectSize         :
ApplicationArguments              :
OpenTimeout                       : 00:04:00
CancelTimeout                     : 00:01:00
IdleTimeout                       : 00:04:00

Description
-----------
This example demonstrates that you can edit the session option object. All properties have read/write values.

Use this method to create a standard session object for your enterprise, and then create customized versions of it for particular uses.

Example 5

C:\PS>$PSSessionOption = New-PSSessionOption -OpenTimeOut 120000

This command creates a $PSSessionOption preference variable.

When the $PSSessionOption preference variable exists in the session, it establishes default values for options in the PSSessions that are created by using the New-PSSession, Enter-PSSession, and Invoke-Command cmdlets.

To make the $PSSessionOption variable available in all sessions, add it to your Windows PowerShell session and to your Windows PowerShell profile.

For more information about the $PSSessionOption variable, see about_Preference_Variables. For more information about profiles, see about_Profiles.

Example 6

C:\PS>$skipCN = new-pssessionoption -SkipCNCheck

C:\PS> new-pssession -computername 171.09.21.207 -UseSSL -credential domain01\user01 -sessionOption $skipCN

Description
-----------
This example shows how to use a SessionOption object to fulfill the requirements for a remote session configuration.

The first command uses the New-PSSessionOption cmdlet to create a session option object with the SkipCNCheck property. The command saves the resulting session object in the $skipCN variable.

The second command uses the New-PSSession cmdlet to create a new PSSession on a remote computer. The $skipCN check variable is used in the value of the SessionOption parameter.

Because the computer is identified by its IP address, the value of the ComputerName parameter does not match any of the common names in the certificate used for Secure Sockets Layer (SSL). As a result, the SkipCNCheck option is required.

See Also

  • Enter-PSSession
  • New-PSSession
  • Invoke-Command


New-Service

Creates a new Windows service.

Syntax

New-Service [-Name] <string> [-BinaryPathName] <string> [-Credential <PSCredential>] [-DependsOn <string[]>] [-Description <string>] [-DisplayName <string>] [-StartupType {<Automatic> | <Manual> | <Disabled>}] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The New-Service cmdlet creates a new entry for a Windows service in the registry and in the service database. A new service requires an executable file that executes during the service.

The parameters of this cmdlet let you set the display name, description, startup type, and dependencies of the service.

Parameters

-BinaryPathName <string>

Specifies the path to the executable file for the service. This parameter is required.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one from the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DependsOn <string[]>

Specifies the names of other services upon which the new service depends. To enter multiple service names, use a comma to separate the names.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Description <string>

Specifies a description of the service.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DisplayName <string>

Specifies a display name for the service.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies the name of the service. This parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-StartupType <ServiceStartMode>

Sets the startup type of the service. "Automatic" is the default.

Valid values are:

-- Manual: The service is started only manually, by a user (using the Service Control Manager) or by an application.

-- Automatic: The service is to be started (or was started) by the operating system, at system start-up. If an automatically started service depends on a manually started service, the manually started service is also started automatically at system startup.

-- Disabled: The service is disabled and cannot be started by a user or application.

Required? | false
Position? | named
Default Value | Automatic
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.ServiceProcess.ServiceController New-Service returns an object that represents the new service.

Notes

To run this cmdlet on Windows Vista and later versions of Windows, start Windows PowerShell with the "Run as administrator" option.

Example 1

C:\PS>new-service -name TestService -binaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

This command creates a new service named "TestService".

Example 2

C:\PS>new-service -name TestService -path "C:\WINDOWS\System32\svchost.exe -k netsvcs" -dependson NetLogon -displayName "Test Service" -StartupType Manual -Description "This is a test service."

This command creates a new service named "TestService". It uses the parameters of the New-Service cmdlet to specify a description, startup type, and display name for the new service.

To specify the BinaryPathName parameter, the command uses the Path parameter alias. You can also use "-bpn".

Example 3

C:\PS>get-wmiobject win32_service -filter "name='testservice'"

ExitCode  : 0
Name      : testservice
ProcessId : 0
StartMode : Auto
State     : Stopped
Status    : OK

Description
-----------
This command uses the Get-WmiObject cmdlet to get the Win32_Service object for the new service. This object includes the start mode and the service description.

See Also

  • Get-Service
  • Start-Service
  • Stop-Service
  • Restart-Service
  • Resume-Service
  • Set-Service
  • Suspend-Service


New-TimeSpan

Creates a TimeSpan object.

Syntax

New-TimeSpan [[-Start] <DateTime>] [[-End] <DateTime>] [<CommonParameters>]

New-TimeSpan [-Days <int>] [-Hours <int>] [-Minutes <int>] [-Seconds <int>] [<CommonParameters>]

Description

The New-TimeSpan cmdlet creates a TimeSpan object that represents a time. interval You can use a TimeSpan object to add or subtract time from DateTime objects.

Without parameters, a "New-Timespan" command returns a timespan object that represents a time interval of zero.

Parameters

-Days <int>

Indicates the days in the time span. The default is 0.

Required? | false
Position? | named
Default Value | 0
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-End <DateTime>

Indicates the end of a time span. The default is the current date and time.

Required? | false
Position? | 2
Default Value | Current date and time
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Hours <int>

Indicates the hours in the time span. The default is zero.

Required? | false
Position? | named
Default Value | 0
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Minutes <int>

Indicates the minutes in the time span. The default is 0.

Required? | false
Position? | named
Default Value | 0
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Seconds <int>

Indicates the length of the time span in seconds. The default is 0.

Required? | false
Position? | named
Default Value | 0
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Start <DateTime>

Indicates the start of a time span. Enter a string that represents the date and time, such as "3/15/09" or a DateTime object, such as one from a Get-Date command.

The default is the current date and time.

Required? | false
Position? | 1
Default Value | Current date and time
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.DateTime You can pipe a DateTime object that represents that start time to New-TimeSpan.
Outputs | System.Timespan New-TimeSpan returns an object that represents the time span.

Example 1

C:\PS>$timespan = new-timespan -hour 1 -minute 25

This command creates a TimeSpan object with a duration of 1 hour and 25 minutes and stores it in a variable named $timespan. It displays a representation of the TimeSpan object.

Example 2

C:\PS>new-timespan -end (get-date -year 2010 -month 1 -day 1)

This example creates a new TimeSpan object that represents the interval between the time that the command is run and January 1, 2010.

This command does not require the Start parameter, because the default value of the Start parameter is the current date and time.

Example 3

C:\PS>$90days = new-timespan -days 90

C:\PS> (get-date) + $90days

These commands return the date that is 90 days after the current date.

See Also

  • Set-Date
  • Get-Date


New-Variable

Creates a new variable.

Syntax

New-Variable [-Name] <string> [[-Value] <Object>] [-Description <string>] [-Force] [-Option {<None> | <ReadOnly> | <Constant> | <Private> | <AllScope>}] [-PassThru] [-Scope <string>] [-Visibility {<Public> | <Private>}] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The New-Variable cmdlet creates a new variable in Windows PowerShell. You can assign a value to the variable while creating it or assign or change the value after it is created.

You can use the parameters of New-Variable to set the properties of the variable (such as those that create read-only or constant variables), set the scope of a variable, and determine whether variables are public or private.

Typically, you create a new variable by typing the variable name and its value, such as "$var = 3", but you can use the New-Variable cmdlet to use its parameters.

Parameters

-Description <string>

Specifies a description of the variable.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows you to create a new variable with the same name as an existing read-only variable.

By default, you can overwrite a variable unless the variable has an option value of ReadOnly or Constant. For more information, see the Option parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies a name for the new variable.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Option <ScopedItemOptions>

Sets the value of the Options property of the new variable.

Valid values are:

-- None: Sets no options. ("None" is the default.)

-- ReadOnly: The value of the variable cannot be changed except by using the Force parameter. You can use Remove-Variable to delete the variable.

-- Constant: The variable cannot be deleted, and its properties cannot be changed. "Constant" is available only when you are creating an alias. You cannot change the option of an existing variable to "Constant".

-- Private: The variable is available only within the scope specified by the Scope parameter. It is inherited by child scopes. (This value is not related to the "Private" value of the Visibility parameter.)

-- AllScope: The variable is copied to any new scopes that are created.

To see the Options property of the variables, type "get-variable| Format-Table -property name, options -autosize".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the new variable. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Scope <string>

Determines the scope of the new variable. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Value <Object>

Specifies the initial value of the variable.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Visibility <SessionStateEntryVisibility>

Determines whether the variable is visible outside of the session in which it was created. This parameter is designed for use in scripts and commands that will be delivered to other users.

Valid values are:

-- Public: The variable is visible. ("Public" is the default.)

-- Private: The variable is not visible.

When a variable is private, it does not appear in lists of variables, such as those returned by Get-Variable, or in displays of the Variable: drive. Commands to read or change the value of a private variable return an error. However, the user can run commands that use a private variable if the commands were written in the session in which the variable was defined.

Required? | false
Position? | named
Default Value | Public
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Object You can pipe a value to New-Variable.
Outputs | None or System.Management.Automation.PSVariable When you use the PassThru parameter, New-Variable generates a System.Management.Automation.PSVariable object representing the new variable. Otherwise, this cmdlet does not generate any output.

Example 1

C:\PS>new-variable days

This command creates a new variable named "days". It has no value immediately following the command.

Example 2

C:\PS>new-variable zipcode -value 98033

This command creates a variable named "zipcode" and assigns it the value "98033".

Example 3

C:\PS>new-variable -name max -value 256 -option readonly

new-variable -name max -value 1024

new-variable -name max -value 1024 -force

C:\PS> new-variable -name max -value 256 -option readonly

C:\PS> new-variable -name max -value 1024
New-Variable : A variable with name 'max' already exists.
At line:1 char:13
+ new-variable <<<<  -name max -value 1024

C:\PS> new-variable -name max -value 1024 -force

Description
-----------
This example shows how to use the ReadOnly option of New-Variable to protect a variable from being overwritten.

The first command creates a new variable named Max and sets its value to "256". It uses the Option parameter with a value of ReadOnly.

The second command tries to create a second variable with the same name. This command returns an error, because the read-only option is set on the variable.

The third command uses the Force parameter to override the read-only protection on the variable. In this case, the command to create a new variable with the same name succeeds.

Example 4

C:\PS>new-variable -name counter -visibility private

#Effect of private variable in a module.

C:\PS> get-variable c*

Name                           Value
----                           -----
Culture                        en-US
ConsoleFileName
ConfirmPreference              High
CommandLineParameters          {}

C:\PS> $counter
"Cannot access the variable '$counter' because it is a private variable"

C:\PS> Get-Counter
Name         Value
----         -----
Counter1     3.1415
...

Description
-----------
This command demonstrates the behavior of a private variable in a module. The module contains the Get-Counter cmdlet, which has a private variable named "Counter". The command uses the Visibility parameter with a value of "Private" to create the variable.

The sample output shows the behavior of a private variable. The user who has loaded the module cannot view or change the value of the Counter variable, but the Counter variable can be read and changed by the commands in the module.

See Also

  • Get-Variable
  • Set-Variable
  • Remove-Variable
  • Clear-Variable


New-WebServiceProxy

Creates a Web service proxy object that lets you use and manage the Web service in Windows PowerShell.

Syntax

New-WebServiceProxy [-URI] <Uri> [[-Class] <string>] [[-Namespace] <string>] [<CommonParameters>]

New-WebServiceProxy [-URI] <Uri> [[-Class] <string>] [[-Namespace] <string>] [-Credential <PSCredential>] [<CommonParameters>]

New-WebServiceProxy [-URI] <Uri> [[-Class] <string>] [[-Namespace] <string>] [-UseDefaultCredential] [<CommonParameters>]

Description

The New-WebServiceProxy cmdlet lets you use a Web service in Windows PowerShell. The cmdlet connects to a Web service and creates a Web service proxy object in Windows PowerShell. You can use the proxy object to manage the Web service.

A Web service is an XML-based program that exchanges data over a network, particularly over the Internet. The Microsoft .NET Framework provides Web service proxy objects that represent the Web service as a .NET Framework object.

Parameters

-Class <string>

Specifies a name for the proxy class that the cmdlet creates for the Web service. The value of this parameter is used with the Namespace parameter to provide a fully qualified name for the class. The default value is generated from the URI.

Required? | false
Position? | 2
Default Value | Generated from the URI
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. This is an alternative to using the UseDefaultCredential parameter.

Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Namespace <string>

Specifies a namespace for the new class.

The value of this parameter is used with the value of the Class parameter to generate a fully qualified name for the class. The default value is Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes plus a type that is generated from the URI.

You can set the value of the Namespace parameter so that you can access multiple Web services with the same name.

Required? | false
Position? | 3
Default Value | Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-URI <Uri>

Specifies the URI of the Web service. Enter a URI or the path and file name of a file that contains a service description.

The URI must refer to an .asmx page or to a page that returns a service description. To return a service description of a Web service that was created by using ASP.NET, append "?WSDL" to the URL of the Web service (for example, http://www.contoso.com/MyWebService.asmx?WSDL).

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseDefaultCredential

Sets the UseDefaultCredential parameter in the resulting proxy object to True. This is an alternative to using the Credential parameter.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not take input from the pipeline.
Outputs | A Web service proxy object The namespace and class of the object are determined by the parameters of the command. The default is generated from the input Uniform Resource Identifier (URI).

Notes

New-WebServiceProxy uses the System.Net.WebClient class to load the specified Web service.

Example 1

C:\PS>$zip = New-WebServiceProxy -uri http://www.webservicex.net/uszip.asmx?WSDL

This command uses the New-WebServiceProxy command to create a .NET Framework proxy of the US Zip Web service in Windows PowerShell.

Example 2

C:\PS>$URI = "http://www.webservicex.net/uszip.asmx?WSDL"

C:\PS> $zip = New-WebServiceProxy -uri $URI -namespace WebServiceProxy -class ZipClass

This command uses the New-WebServiceProxy cmdlet to create a .NET Framework proxy of the US Zip Web service.

The first command stores the URI of the Web service in the $URI variable.

The second command creates the Web service proxy. The command uses the URI parameter to specify the URI and the Namespace and Class parameters to specify the namespace and class of the object.

Example 3

C:\PS>$zip | get-member -type method

TypeName: WebServiceProxy.USZip

Name                      MemberType Definition
----                      ---------- ----------
Abort                     Method     System.Void Abort(
BeginGetInfoByAreaCode    Method     System.IAsyncResul
BeginGetInfoByCity        Method     System.IAsyncResul
BeginGetInfoByState       Method     System.IAsyncResul
BeginGetInfoByZIP         Method     System.IAsyncResul
CreateObjRef              Method     System.Runtime.Rem
Discover                  Method     System.Void Discov
Dispose                   Method     System.Void Dispos
EndGetInfoByAreaCode      Method     System.Xml.XmlNode
EndGetInfoByCity          Method     System.Xml.XmlNode
EndGetInfoByState         Method     System.Xml.XmlNode
EndGetInfoByZIP           Method     System.Xml.XmlNode
Equals                    Method     System.Boolean Equ
GetHashCode               Method     System.Int32 GetHa
GetInfoByAreaCode         Method     System.Xml.XmlNode
GetInfoByCity             Method     System.Xml.XmlNode
GetInfoByState            Method     System.Xml.XmlNode
GetInfoByZIP              Method     System.Xml.XmlNode
GetLifetimeService        Method     System.Object GetL
GetType                   Method     System.Type GetTyp
InitializeLifetimeService Method     System.Object Init
ToString                  Method     System.String ToSt

Description
-----------
This command uses the Get-Member cmdlet to display the methods of the Web service proxy object in the $zip variable. We will use these methods in the following example.

Notice that the TypeName of the proxy object, WebServiceProxy, reflects the namespace and class names that were specified in the previous example.

Example 4

C:\PS>$zip.getinfobyzip(20500).table

CITY      : Washington
STATE     : DC
ZIP       : 20500
AREA_CODE : 202
TIME_ZONE : E

Description
-----------
This command uses the Web service proxy stored in the Zip variable. The command uses the GetInfoByZip method of the proxy and its Table property.

See Also

  • New-Service


New-WSManInstance

Creates a new instance of a management resource.

Syntax

New-WSManInstance [-ApplicationName <string>] [-ComputerName <string>] [-Credential <PSCredential>] [-Port <int>] [-UseSSL] [-SelectorSet] <hashtable> -ResourceURI <Uri> [-AuthenticationMechanism <AuthenticationMechanism>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

New-WSManInstance [-ConnectionURI <Uri>] [-SelectorSet] <hashtable> -ResourceURI <Uri> [-AuthenticationMechanism <AuthenticationMechanism>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

Description

The New-WSManInstance cmdlet creates a new instance of a management resource. It uses a resource URI and a value set or input file to create the new instance of the management resource.

This cmdlet uses the WinRM connection/transport layer to create the management resource instance.

Parameters

-ApplicationName <string>

Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for the remote endpoint is in the following format:

<transport>://<server>:<port>/<ApplicationName>

For example:

http://server01:8080/WSMAN

Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency.

Required? | false
Position? | named
Default Value | wsman
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AuthenticationMechanism <AuthenticationMechanism>

Specifies the authentication mechanism to be used at the server. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.

- Default : Use the authentication method implemented by the WS-Management protocol. This is the default.

- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

- Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates.

- Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.

- CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

Caution: CredSSP delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

Required? | false
Position? | named
Default Value | localhost
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ConnectionURI <Uri>

Specifies the connection endpoint. The format of this string is:

<Transport>://<Server>:<Port>/<ApplicationName>

The following string is a properly formatted value for this parameter:

http://Server01:8080/WSMAN

The URI must be fully qualified.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Domain.com". Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-File <File>

Specifies the path of a file that is used to create a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter . For example, the following command uses the File parameter:

invoke-wsmanaction -action stopservice -resourceuri wmicimv2/Win32_Service -SelectorSet @{Name="spooler"} -File c:\input.xml -authentication default

This command calls the StopService method [descriptor] on the Spooler service by using input from a file. The file, Input.xml, contains the following content:

<p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service"/>

Required? |
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OptionSet <hashtable>

Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified.

The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters:

-OptionSet @{a=1;b=2;c=3}

Required? |
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Port <int>

Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server's certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted computers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ResourceURI <Uri>

Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer.

A URI consists of a prefix and a path to a resource. For example:

http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk

http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SelectorSet <hashtable>

Specifies a set of value pairs that are used to select particular management resource instances. The SelectorSet parameter is used when more than one instance of the resource exists. The value of the SelectorSet parameter must be a hash table.

The following example shows how to enter a value for this parameter:

-SelectorSet @{Name="WinRM";ID="yyy"}

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-SessionOption <hashtable>

Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, see New-WSManSessionOption.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ValueSet <hashtable>

Specifies a hash table that helps modify a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. The value of the ValueSet parameter must be a hash table.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Notes

The Set-WmiInstance cmdlet, a Windows Management Instrumentation (WMI) cmdlet, is similar. Set-WmiInstance uses the DCOM connection/transport layer to create or update WMI instances.

Example 1

C:\PS>New-WSManInstance winrm/config/Listener -SelectorSet @{Transport=HTTPS} -ValueSet @{Hostname="HOST";CertificateThumbprint="XXXXXXXXXX"}

This command creates an instance of a WS-Management HTTPS listener on all IP addresses.

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


New-WSManSessionOption

Creates a WS-Management session option hash table to use as input parameters to the following WS-Management cmdlets: Get-WSManInstance Set-WSManInstance Invoke-WSManAction Connect-WSMan

Syntax

New-WSManSessionOption [-NoCompression <switch>] [-NoProxy <switch>] [-ProxyAuthentication <string>] [-ProxyPassword <string>] [-ProxyUserName <string>] [-SkipCACheck <switch>] [-SkipCNCheck <switch>] [-SkipRevocation <switch>] [-SPNPort <int>] [-Timeout <int>] [-UnEncrypted <switch>] [-UseIEProxyconfig <switch>] [-UseProxyAutoDetection <switch>] [-UseWinHTTPProxyConfig <switch>] [-UTF16 <switch>] [<CommonParameters>]

Description

Creates a WSMan Session option hashtable which can be passed into WSMan cmdlets:

Get-WSManInstance

Set-WSManInstance

Invoke-WSManAction

Connect-WSMan

Parameters

-NoCompression <switch>

Turns off packet compression in the session. Compression is enabled by default and the packets sent between the client and server are compressed. Compression uses more processor cycles, but it makes transmission faster.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoProxy <switch>

Do not use a proxy server. All all host names will be resolved locally.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ProxyAuthentication <string>

Specifies the authentication method to use at the proxy. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear-text to the server or proxy.

- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

- Negotiate (the default): Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine which scheme to use for authentication. Examples are the Kerberos protocol and NTLM.

Required? | false
Position? | named
Default Value | Negotiate
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ProxyPassword <string>

Specifies a password to to be used for proxy authentication.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ProxyUserName <string>

Specifies a user name to to be used for proxy authentication.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SkipCACheck <switch>

Specifies that when connecting over HTTPS, the client does not validate that the server certificate is signed by a trusted certificate authority (CA). Use this option only when the remote computer is trusted by other means, for example, if the remote computer is part of a network that is physically secure and isolated or the remote computer is listed as a trusted host in the WS-Management configuration.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SkipCNCheck <switch>

Specifies that the certificate common name (CN) of the server does not need to match the hostname of the server. This is used only in remote operations using HTTPS. This option should only be used for trusted computers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SkipRevocation <switch>

Do not validate the revocation status on the server certificate.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SPNPort <int>

Specifies a port number to append to the connection Service Principal Name <SPN> of the remote server. An SPN is used when the authentication mechanism is Kerberos or Negotiate.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Timeout <int>

Defines the timeout in milliseconds for the WS-Management operation.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UnEncrypted <switch>

Do not use encryption when doing remote operations over HTTP.

Note: Unencrypted traffic is not allowed by default and must be enabled in the local configuration.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseIEProxyconfig <switch>

Use the Internet Explorer proxy configuration for the current user. This is the default setting.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseProxyAutoDetection <switch>

Force auto-detection of a proxy.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseWinHTTPProxyConfig <switch>

Use the proxy settings configured for WinHTTP.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UTF16 <switch>

Encode the request in UTF16 format rather than UTF8 format. The default is UTF8 encoding.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs |
Outputs | SessionOption

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


Out-Default

Sends the output to the default formatter and to the default output cmdlet.

Syntax

Out-Default [-InputObject <psobject>] [<CommonParameters>]

Description

The Out-Default cmdlet sends output to the default formatter and the default output cmdlet. This cmdlet has no effect on the formatting or output of Windows PowerShell commands. It is a placeholder that lets you write your own Out-Default function or cmdlet.

Parameters

-InputObject <psobject>

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs

Outputs


Out-File

Sends output to a file.

Syntax

Out-File [-FilePath] <string> [[-Encoding] <string>] [-Append] [-Force] [-InputObject <psobject>] [-NoClobber] [-Width <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Out-File cmdlet sends output to a file. You can use this cmdlet instead of the redirection operator (>) when you need to use its parameters.

Parameters

-Append

Adds the output to the end of an existing file, instead of replacing the file contents.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Encoding <string>

Specifies the type of character encoding used in the file. Valid values are "Unicode", "UTF7", "UTF8", "UTF32", "ASCII", "BigEndianUnicode", "Default", and "OEM". "Unicode" is the default.

"Default" uses the encoding of the system's current ANSI code page.

"OEM" uses the current original equipment manufacturer code page identifier for the operating system.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilePath <string>

Specifies the path to the output file.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to overwrite an existing read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be written to the file. Enter a variable that contains the objects or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-NoClobber

Will not overwrite (replace the contents) of an existing file. By default, if a file exists in the specified path, Out-File overwrites the file without warning. If both Append and NoClobber are used, the output is appended to the existing file.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Width <int>

Specifies the number of characters in each line of output. Any additional characters are truncated, not wrapped. If you omit this parameter, the width is determined by the characteristics of the host. The default for the Windows PowerShell console is 80 (characters).

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Out-File.
Outputs | None Out-File does not generate any output.

Notes

The Out cmdlets do not format objects; they just render them and send them to the specified display destination. If you send an unformatted object to an Out cmdlet, the cmdlet sends it to a formatting cmdlet before rendering it.

The Out cmdlets do not have parameters for names or file paths. To send data to a cmdlet that contains the Out verb (an Out cmdlet), use a pipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the InputObject parameter to pass the data to the cmdlet. For help, see the examples.

Out-File sends data, but it does not emit any output objects. If you pipe the output of Out-File to Get-Member, Get-Member reports that no objects have been specified.

Example 1

C:\PS>get-process | out-file -filepath C:\Test1\process.txt

This command sends a list of processes on the computer to the Process.txt file. If the file does not exist, Out-File creates it. Because the name of the FilePath parameter is optional, you can omit it and submit the equivalent command "get-process | outfile C:\Test1\process.txt".

Example 2

C:\PS>get-process | out-file C:\Test1\process.txt -noclobber

Out-File : File C:\Test1\process.txt already exists and NoClobber was specified.
At line:1 char:23
+ get-process | out-file  <<<< process.txt -noclobber

Description
-----------
This command also sends a list of processes to the Process.txt file, but it uses the NoClobber parameter, which prevents an existing file from being overwritten. The output shows the error message that appears when NoClobber is used with an existing file.

Example 3

C:\PS>$a = get-process

C:\PS> out-file -filepath C:\Test1\process.txt -inputobject $a -encoding ASCII -width 50

These commands send a list of processes on the computer to the Process.txt file. The text is encoded in ASCII format so that it can be read by search programs like Findstr and Grep. By default, Out-File uses Unicode format.

The first command gets the list of processes and stores them in the $a variable. The second command uses the Out-File cmdlet to send the list to the Process.txt file.

The command uses the InputObject parameter to specify that the input is in the $a variable. It uses the Encoding parameter to convert the output to ASCII format. It uses the Width parameter to limit each line in the file to 50 characters. Because the lines of output are truncated at 50 characters, the rightmost column in the process table is omitted.

Example 4

C:\PS>set-location hklm:\software

c:\PS>get-acl mycompany\mykey | out-file -filepath c:\ps\acl.txt

c:\PS>get-acl mycompany\mykey | out-file -filepath filesystem::acl.txt

These commands show how to use the Out-File cmdlet when you are not in a FileSystem drive.

The first command sets the current location to the HKLM:\Software registry key.

The second and third commands have the same effect. They use the Get-Acl cmdlet to get the security descriptor of the MyKey registry subkey (HKLM\Software\MyCompany\MyKey). A pipeline operator passes the result to the Out-File cmdlet, which sends it to the Acl.txt file.

Because Out-File is not supported by the Windows PowerShell Registry provider, you must specify either the file system drive name, such as "c:", or the name of the provider followed by two colons, "FileSystem::", in the value of the FilePath parameter. The second and third commands demonstrate these methods.

See Also

  • Out-String
  • Out-Null
  • Out-Host
  • Out-Printer
  • Out-Default
  • Tee-Object


Out-GridView

Sends output to an interactive table in a separate window.

Syntax

Out-GridView [-InputObject <psobject>] [-Title <string>] [<CommonParameters>]

Description

The Out-GridView cmdlet sends the output from a command to a grid view window where the output is displayed in an interactive table. This feature requires Microsoft .NET Framework 3.5 with Service Pack 1.

You can use the following features of the table to examine your data:

-- Hide, Show, and Reorder Columns: To hide, show, or reorder a column, right-click a column header and then click "Select Columns."

-- Sort. To sort the data, click a column header. Click again to toggle from ascending to descending order.

-- Quick Filter. Use the "Filter" box at the top of the window to search the text in the table. You can search for text in a particular column, search for literals, and search for multiple words.

-- Criteria Filter. Use the "Add criteria" drop-down menu to create rules to filter the data. This is very useful for very large data sets, such as event logs.

-- Copy and paste. To copy rows of data from Out-GridView, press CTRL+C (copy). You can paste the data into any text or spreadsheet program.

For instructions for using these features, type "Get-Help out-gridview -full" and see "How to Use the Grid View Window Features" in the NOTES section.

Parameters

-InputObject <psobject>

Accepts input for Out-GridView.

When you use the InputObject parameter to send a collection (more than one) of objects to Out-GridView, Out-GridView treats the collection as one collection object, and it displays one row that represents the collection. To display the each object in the collection, use a pipeline operator (|) to send objects to Out-GridView.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Title <string>

Specifies the text that appears in the title bar of the Out-GridView window.

By default, the title bar displays the command that invokes Out-GridView.

Required? | false
Position? | named
Default Value | The current command
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can send any object to Out-GridView.
Outputs | None Out-GridView does not return any objects.

Notes

NOTES FOR OUT-GRIDVIEW

----------------------

You can download the Microsoft .NET Framework 3.5 with Service Pack 1 from the Microsoft Download Center.

Because this cmdlet requires a user interface, it does not work on Server Core installations of Windows Server.

You cannot use a remote command to open a grid view window on a remote computer.

The command output that you send cannot be pre-formatted, such as by using the Format-Table or Format-Wide cmdlets. To select properties, use the Select-Object cmdlet.

Deserialized output from remote commands might not be formatted correctly in the grid view window.

KEYBOARD SHORTCUTS FOR OUT-GRIDVIEW

-----------------------------------

By using the following Keyboard Shortcuts, you can perform many tasks quickly.

Use this key: To perform this action:

------------- ----------------------------------------------------------------

TAB Moves the cursor from the Filter box to the Add criteria menu to the table and back.

UP ARROW Move up one row. Will move to column headers.

DOWN ARROW Move down one row.

LEFT ARROW In column header row, move left one column.

RIGHT ARROW In column header row, move right one column.

CONTEXT MENU KEY In column header row, displays the "Select Columns" option.

ENTER or SPACEBAR In column header row, sort column data (toggle A-Z, Z-A).

HOW TO USE THE GRID VIEW WINDOW FEATURES

----------------------------------------

The following topics explain how to use the features of the window that Out-GridView displays.

How to Hide, Show, and Reorder Columns

--------------------------------------

To hide or show a column:

1. Right click any column header and click "Select Columns".

2. In the "Select Columns" dialog box, use the arrow keys to move the columns between the "Selected columns" to the "Available columns" boxes. Only columns in the "Selected Columns" box appear in the grid view window.

To reorder columns:

-- Drag and drop the column into the desired location.

- or-

1. Right click any column header and click "Select Columns".

2. In the "Select Columns" dialog box, use the "Move up" and "Move down" buttons to reorder the columns. Columns at the top of the list appear to the left of columns at the bottom of the list in the grid view window.

How to Sort Table Data

----------------------

-- To sort the data, click a column header.

-- To change the sort order, click the column header again. Each time you click the same header, the sort order toggles between ascending to descending order. The current order is indicated by a triangle in the column header.

How to Select Table Data

------------------------

-- To select a row, click the row or use the up or down arrow to navigate to the row.

-- To select all rows (except for the header row), press CTRL+A.

-- To select consecutive rows, press and hold the SHIFT key while clicking the rows or using the arrow keys.

-- To select nonconsecutive rows, press the CTRL key and click to add a row to the selection.

You cannot select columns, and you cannot select the entire column header row.

How to Copy Rows

----------------------

-- To copy one or more rows from the table, select the rows and then press CTRL+C.

You can paste the data into any text or spreadsheet program. You cannot copy columns or parts of rows and you cannot copy the column header row.

How to Search in the Table (Quick Filter)

---------------------------------

Use the "Filter" box to search for data in the table. When you type in the box, only items that include the typed text appear in the table.

-- Search for text. To search for text in the table, in the "Filter" box, type the text to find.

-- Search for multiple words. To search for multiple words in the table, type the words separated by spaces. Out-GridView displays rows that include all of the words (logical AND).

-- Search for literal phrases. To search for phrases that include spaces or special characters, enclose the phrase in quotation marks. Out-GridView displays rows that include an exact match for the phrase.

-- Search in columns. To search for text in one or more columns, use the following format:

<column>:<text> [<column>:<text>] ...

For example, to find "Net" in the DisplayName column, in the "Filter" box, type:

displayname:net

To find rows with "Net" in the DisplayName and Name columns, in the "Filter" box, type:

displayname:net name:net

-- Turn off search. To display the entire table again, click the red X button in the top right corner of the "Filter" box or delete the text from the Filter box.

Use Criteria to Filter the Table

--------------------------------

You can use rules or "criteria" to determine which items are displayed in the table. Items appear only when they satisfy all of the criteria that you establish. The available criteria are determined by the properties of the objects displayed in the grid view window and the .NET Framework types of those properties.

Each criterion has the following format:

<column> <operator> <value>

Criteria for different properties are connected by AND. Criteria for the same property are connected by OR. You cannot change the logical connectors.

The criteria only affects the display. It does not delete items from the table.

How to Add Criteria

---------------------------

1. To display the "Add criteria" menu button, in the upper right corner of the window, click the "Expand" arrow.

2. Click the "Add Criteria" menu button.

3. Click to select columns (properties). You can select one or many properties.

4. When you are finished selecting properties, click the Add button.

5. To cancel the additions, click Cancel.

6. To add more criteria, click the Add Criteria button again.

How to Edit a Criterion

--------------------

-- To change an operator, click the blue operator value, and then click to select a different

operator from the drop-down list.

-- To enter or change a value, type a value in the value box. If you enter a value that is not valid, a circular X icon appears. To remove it, change the value.

-- To create an OR statement, add a criteria with the same property.

How to Delete Criteria

-------------------------

-- To delete selected criteria, click the red X beside each criterion.

-- To delete all criteria, click the "Clear All" button.

Example 1

C:\PS>get-process | out-gridview

This command gets the processes running on the local computer and sends them to a grid view window.

Example 2

C:\PS>$p = get-process

C:\PS> $p | out-gridview

This command also gets the processes running on the local computer and sends them to a grid view window.

The first command uses the Get-Process command to get the processes on the computer and then saves the process objects in the $p variable.

The second command uses a pipeline operator to send the $p variable to Out-GridView.

Example 3

C:\PS>get-process | select-object -property name, workingset, peakworkingset | sort-object -property workingset -desc | out-gridview

This command displays a formatted table in a grid view window.

It uses the Get-Process cmdlet to get the processes on the computer.

Then, it uses a pipeline operator (|) to send the process objects to the Select-Object cmdlet. The command uses the Property parameter of Select-Object to select the Name, WorkingSet, and PeakWorkingSet properties to be displayed in the table.

Another pipeline operator sends the filtered objects to the Sort-Object cmdlet, which sorts them in descending order by the value of the WorkingSet property.

The final part of the command uses a pipeline operator (|) to send the formatted table to Out-GridView.

You can now use the features of the grid view to search, sort, and filter the data.

Example 4

C:\PS>($a = get-childitem -path $pshome -recurse) | out-gridview

This command saves its output in a variable and sends it to Out-GridView.

The command uses the Get-ChildItem cmdlet to get the files in the Windows PowerShell installation directory and its subdirectories. The path to the installation directory is saved in the $pshome automatic variable.

The command uses the assignment operator (=) to save the output in the $a variable and the pipeline operator (|) to send the output to Out-GridView.
The parentheses in the command establish the order of operations. As a result, the output from the Get-ChildItem command is saved in the $a variable before it is sent to Out-GridView.

Example 5

C:\PS>get-process -computername Server01| ogv -title "Processes - Server01"

This command displays the processes that are running on the Server01 computer in a grid view window.

The command uses "ogv," which is the built-in alias for the Out-GridView cmdlet, it uses the Title parameter to specify the window title.

Example 6

C:\PS>invoke-command -ComputerName S1, S2, S3 -scriptblock {get-culture} | out-gridview

This example shows the correct format for sending data collected from remote computers to the Out-GridView cmdlet.

The command uses the Invoke-Command cmdlet to run a Get-Culture command on three remote computers. It uses a pipeline operator to send the data that is returned to the Out-GridView cmdlet.

Notice that the script block that contains the commands that are run remotely does not include the Out-GridView command. If it did, the command would fail when it tried to open a grid view window on each of the remote computers.


Out-Host

Sends output to the command line.

Syntax

Out-Host [-InputObject <psobject>] [-Paging] [<CommonParameters>]

Description

The Out-Host cmdlet sends output to the Windows PowerShell host for display. The host displays the output at the command line. Because Out-Host is the default, you do not need to specify it unless you want to use its parameters to change the display.

Parameters

-InputObject <psobject>

Specifies the objects that are written to the console. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Paging

Displays one page of output at a time, and waits for user input before displaying the remaining pages, much like the traditional "more" command. By default, all of the output is displayed on a single page. The page size is determined by the characteristics of the host.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Out-Host.
Outputs | None Out-Host does not generate any output. However, the host might display the objects that Out-Host sends to it.

Notes

You can also refer to Out-Host by its built-in alias, "oh". For more information, see about_Aliases.

The cmdlets that contain the Out verb (the Out cmdlets) do not format objects; they just render them and send them to the specified display destination. If you send an unformatted object to an Out cmdlet, the cmdlet sends it to a formatting cmdlet before rendering it.

The Out cmdlets do not have parameters for names or file paths. To send data to an Out cmdlet, use a pipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the InputObject parameter to pass the data to the cmdlet. For help, see the examples.

Out-Host sends data, but it does not emit any output objects. If you pipe the output of Out-Host to Get-Member, Get-Member reports that no objects have been specified.

Example 1

C:\PS>get-process | out-host -paging

This command displays the processes on the system one page at a time. It uses the Get-Process command to get the processes on the system. The pipeline operator (|) sends the results to Out-Host, which displays them at the console. The Paging parameter displays one page of data at a time.

The same command format is used for the Help function that is built into Windows PowerShell. That function gets data from Get-Help and then uses the Paging parameter of Out-Host to display the data one page at a time by using this command format: get-help $args[0] | out-host -paging).

Example 2

C:\PS>$a = get-history

C:\PS>out-host -InputObject $a

These commands display the session history at the command line. The first command uses the Get-History cmdlet to get the session history, and then it stores the history in the $a variable. The second command uses Out-Host to display the content of the $a variable, and it uses the InputObject parameter to specify the variable to Out-Host.

See Also

  • Out-Printer
  • Out-Null
  • Out-File
  • Out-String
  • Out-Default
  • Write-Host


Out-Null

Deletes output instead of sending it to the console.

Syntax

Out-Null [-InputObject <psobject>] [<CommonParameters>]

Description

The Out-Null cmdlet sends output to NULL, in effect, deleting it.

Parameters

-InputObject <psobject>

Specifies the object that was sent to null (deleted). Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Out-Null.
Outputs | None Out-Null does not generate any output.

Notes

The cmdlets that contain the Out verb (the Out cmdlets) do not have parameters for names or file paths. To send data to an Out cmdlet, use a pipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the InputObject parameter to pass the data to the cmdlet. For more information, see the examples.

Out-Null does not return any output objects. If you pipe the output of Out-Null to Get-Member, Get-Member reports that no objects have been specified.

Example 1

C:\PS>get-childitem | out-null

This command gets the items in the local directory, but then it discards them instead of passing them through the pipeline or displaying them at the command line. This is useful for discarding output that you do not need.

See Also

  • Out-Printer
  • Out-Host
  • Out-File
  • Out-String
  • Out-Default


Out-Printer

Sends output to a printer.

Syntax

Out-Printer [[-Name] <string>] [-InputObject <psobject>] [<CommonParameters>]

Description

The Out-Printer cmdlet sends output to the default printer or to an alternate printer, if one is specified.

Parameters

-InputObject <psobject>

Specifies the objects to be sent to the printer. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string>

Specifies the alternate printer. The parameter name ("Name") is optional.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Out-Printer.
Outputs | None Out-Printer does not return any objects.

Notes

You can also refer to Out-Printer by its built-in alias, "lp". For more information, see about_Aliases.

The cmdlets that contain the Out verb (the Out cmdlets) do not format objects; they just render them and send them to the specified display destination. If you send an unformatted object to an Out cmdlet, the cmdlet sends it to a formatting cmdlet before rendering it.

The Out cmdlets do not have parameters for names or file paths. To send data to an Out cmdlet, use a pipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the InputObject parameter to pass the data to the cmdlet. For more information, see the examples.

Out-Printer sends data, but it does not emit any output objects. If you pipe the output of Out-Printer to Get-Member, Get-Member reports that no objects have been specified.

Example 1

C:\PS>get-content $pshome\about_signing.help.txt | Out-Printer

This command prints the content of the about_Signing Help topic to the default printer. This example shows you how to print a file, even though Out-Printer does not have a Path parameter.

The command uses the Get-Content cmdlet to get the contents of the Help topic. The path includes $pshome, a built-in variable that stores the installation directory for Windows PowerShell. A pipeline operator (|) passes the results to Out-Printer, which sends it to the default printer.

Example 2

C:\PS>"Hello, World" | out-printer -name "\\Server01\Prt-6B Color"

This command prints "Hello, World" to the "Prt-6B Color" printer on Server01. This command uses the Name parameter to specify the alternate printer. Because the parameter name is optional, you can omit it.

Example 3

C:\PS>$h = get-help -full get-wmiobject

C:\PS> out-printer -inputobject $h

These commands print the full version of the Help topic for Get-WmiObject. The first command uses the Get-Help cmdlet to get the full version of the Help topic for Get-WmiObject and stores it in the $h variable. The second command sends the content to the default printer. It uses the InputObject parameter to pass the value of the $h variable to Out-Printer.

See Also

  • Out-Host
  • Out-Null
  • Out-String
  • Out-File
  • Out-Default


Out-String

Sends objects to the host as a series of strings.

Syntax

Out-String [-InputObject <psobject>] [-Stream] [-Width <int>] [<CommonParameters>]

Description

The Out-String cmdlet converts the objects that Windows PowerShell manages into an array of strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the stream parameter to direct Out-String to return one string at a time. This cmdlet lets you search and manipulate string output as you would in traditional shells when object manipulation is less convenient.

Parameters

-InputObject <psobject>

Specifies the objects to be written to a string. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Stream

Sends the strings for each object separately. By default, the strings for each object are accumulated and sent as a single string.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Width <int>

Specifies the number of characters in each line of output. Any additional characters are truncated, not wrapped. If you omit this parameter, the width is determined by the characteristics of the host. The default for the PowerShell.exe host is 80 (characters).

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe objects to Out-String.
Outputs | System.String Out-String returns the string that it creates from the input object.

Notes

The cmdlets that contain the Out verb (the Out cmdlets) do not format objects; they just render them and send them to the specified display destination. If you send an unformatted object to an Out cmdlet, the cmdlet sends it to a formatting cmdlet before rendering it.

The Out cmdlets do not have parameters for names or file paths. To send data to an Out cmdlet, use a pipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the InputObject parameter to pass the data to the cmdlet. For more information, see the examples.

Example 1

C:\PS>get-content C:\test1\testfile2.txt | out-string

This command sends the content of the Testfile2.txt file to the console as a single string. It uses the Get-Content cmdlet to get the content of the file. The pipeline operator (|) sends the content to Out-String, which sends the content to the console as a string.

Example 2

C:\PS>$c = get-culture | select-object *

C:\PS> out-string -inputobject $c -width 100

These commands get the regional settings for the current user and convert the data to strings. The first command uses the Get-Culture cmdlet to get the regional settings. The pipeline operator (|) sends the result to the Select-Object cmdlet, which selects all properties (*) of the culture object that Get-Culture retrieved. The command then stores the results in the $c variable.

The second command uses Out-String to convert the CultureInfo object to a series of strings (one string for each property). It uses the InputObject parameter to pass the $c variable to Out-String. The width parameter is set to 100 characters per line to prevent truncation.

Example 3

C:\PS>get-alias | out-string -stream | select-string "Get-Command"

This command displays aliases that include the phrase "Get-Command". It uses the Get-Alias cmdlet to get a set of AliasInfo objects (one for each alias in the current session). This example demonstrates the difference between working with objects and working with strings.

The pipeline operator (|) sends the output of Get-Alias to Out-String, which converts the objects to a series of strings. It uses the Stream parameter to send each string individually, instead of concatenating them into a single string. Another pipeline operator sends the strings to Select-String, which selects the strings that include "Get-Command" anywhere in the string.

If you omit the Stream parameter, the command displays all of the aliases, because Select-String finds "Get-Command" in the single string that Out-String returns, and the formatter displays the string as a table.

See Also

  • Out-File
  • Out-Null
  • Out-Host
  • Out-Printer
  • Out-Default


Pop-Location

Changes the current location to the location most recently pushed onto the stack. You can pop the location from the default stack or from a stack that you create by using the Push-Location cmdlet.

Syntax

Pop-Location [-PassThru] [-StackName <string>] [-UseTransaction] [<CommonParameters>]

Description

The Pop-Location cmdlet changes the current location to the location most recently pushed onto the stack by using the Push-Location cmdlet. You can pop a location from the default stack or from a stack that you create by using a Push-Location command.

Parameters

-PassThru

Passes an object representing the location to the pipeline. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-StackName <string>

Specifies an alternate stack. Pop-Location pops the most recently added location from this stack. This stack then becomes the current stack.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to Pop-Location.
Outputs | None or System.Management.Automation.PathInfo When you use the PassThru parameter, Pop-Location generates a System.Management.Automation.PathInfo object that represents the location. Otherwise, this cmdlet does not generate any output.

Notes

You can also refer to Pop-Location by its built-in alias, "popd". For more information, see about_Aliases.

The Pop-Location cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>pop-location

This command changes your location to the location most recently added to the current stack.

Example 2

C:\PS>pop-location -stackname Stack2

This command changes your location to the location most recently added to the Stack2 stack.

Example 3

C:\PS>pushd HKLM:\Software\Microsoft\PowerShell

pushd Cert:\LocalMachine\TrustedPublisher

popd

popd

PS C:\> push-location HKLM:\Software\Microsoft\PowerShell

PS HKLM:\Software\Microsoft\PowerShell> push-location Cert:\LocalMachine\TrustedPublisher

PS cert:\LocalMachine\TrustedPublisher> popd

PS HKLM:\Software\Microsoft\PowerShell> popd

PS C:\ps-test>

Description
-----------
These commands use the Push-Location and Pop-Location cmdlets to move between locations supported by different Windows PowerShell providers. The commands use the "pushd" alias for Push-Location and the "popd" alias for Pop-Location.

The first command pushes the current file system location onto the stack and moves to the HKLM drive supported by the Windows PowerShell Registry provider. The second command pushes the registry location onto the stack and moves to a location supported by the Windows PowerShell certificate provider.

The last two commands pop those locations off the stack. The first "popd" command returns to the Registry: drive, and the second command returns to the file system drive.

See Also

  • about_Providers
  • Push-Location
  • Set-Location
  • Get-Location


Push-Location

Adds the current location to the top of a list of locations (a "stack").

Syntax

Push-Location [[-LiteralPath] <string>] [-PassThru] [-StackName <string>] [-UseTransaction] [<CommonParameters>]

Push-Location [[-Path] <string>] [-PassThru] [-StackName <string>] [-UseTransaction] [<CommonParameters>]

Description

The Push-Location cmdlet adds ("pushes") the current location to the top of a list of locations, called a "stack." You can push the current location onto a default stack or onto a stack that you create. If you specify a path, Push-Location pushes the current location onto the stack and then changes the current location to the location specified by the path. You cannot push a location onto the stack unless it is the current location.

Parameters

-LiteralPath <string>

Specifies the path to the new location. Unlike the Path parameter, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Passes an object representing the location to the pipeline. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Changes your location to the location specified by this path after it adds (pushes) the current location onto the top of the stack. Enter a path to any location whose provider supports this cmdlet. Wildcards are permitted. The parameter name ("Path") is optional.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-StackName <string>

Specifies the name of a stack. The current location is pushed onto this stack, and this stack becomes the current stack. If the stack does not yet exist, it is created.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path (but not a literal path) to Push-Location.
Outputs | None or System.Management.Automation.PathInfo When you use the PassThru parameter, Push-Location generates a System.Management.Automation.PathInfo object that represents the location. Otherwise, this cmdlet does not generate any output.

Notes

You can also refer to Push-Location by its built-in alias, "pushd". For more information, see about_Aliases.

A "stack" is a "last-in, first-out" (LIFO) data structure. It is like a vertical list in which only the top item is accessible. You can add ("push") items only to the top of the stack, and you can retrieve ("pop") items only from the top of the stack. To get to items below the top, you must retrieve all the items above.

The Push-Location cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>push-location C:\Windows

This command pushes the current location onto the default stack and then changes the location to C:\Windows.

Example 2

C:\PS>push-location HKLM:\Software\Policies -stackname RegFunction

This command pushes the current location onto the RegFunction stack and changes the current location to the HKLM:\Software\Policies location. This command shows that you can use Push-Location with the Windows PowerShell registry provider.

Example 3

C:\PS>push-location

This command pushes the current location onto the default stack.

Example 4

C:\PS>push-location ~ -stackname Stack2

This command pushes the current location onto a new stack named Stack2 and then changes the current location to the home directory (%USERPROFILE%), which is represented in the command by the tilde symbol (~) or $home. The Stack2 stack then becomes the current stack.

See Also

  • about_Providers
  • Pop-Location
  • Set-Location
  • Get-Location


Read-Host

Reads a line of input from the console.

Syntax

Read-Host [[-Prompt] <Object>] [-AsSecureString] [<CommonParameters>]

Description

The Read-Host cmdlet reads a line of input from the console. You can use it to prompt a user for input. Because you can save the input as a secure string, you can use this cmdlet to prompt users for secure data, such as passwords, as well as shared data.

Parameters

-AsSecureString

Displays asterisks (*) in place of the characters that the user types as input.

When you use this parameter, the output of the Read-Host cmdlet is a SecureString object (System.Security.SecureString).

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Prompt <Object>

Specifies the text of the prompt. Type a string. If the string includes spaces, enclose it in quotation marks. For example, "Type an integer: ".

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.String or System.Security.SecureString If the AsSecureString parameter is used, Read-Host returns a SecureString. Otherwise, it returns a string.

Example 1

C:\PS>$age = read-host "Please enter your age:"

This command displays the string "Please enter your age:" as a prompt. When a value is entered and the Enter key is pressed, the value is stored in the $age variable.

Example 2

C:\PS>$pwd_secure_string = read-host "Enter a Password:" -assecurestring

This command displays the string "Enter a Password:" as a prompt. As a value is being entered, asterisks (*) appear on the console in place of the input. When the Enter key is pressed, the value is stored as a SecureString object in the $pwd_secure_string variable.

See Also

  • Get-Host
  • Out-Host
  • Write-Host
  • ConvertFrom-SecureString


Receive-Job

Gets the results of the Windows PowerShell background jobs in the current session.

Syntax

Receive-Job [-Job] <Job[]> [[-ComputerName] <string[]>] [-Keep] [-NoRecurse] [<CommonParameters>]

Receive-Job [[-InstanceId] <Guid[]>] [-Keep] [-NoRecurse] [<CommonParameters>]

Receive-Job [-Job] <Job[]> [[-Location] <string[]>] [-Keep] [-NoRecurse] [<CommonParameters>]

Receive-Job [[-Name] <string[]>] [-Keep] [-NoRecurse] [<CommonParameters>]

Receive-Job [-Job] <Job[]> [[-Session] <PSSession[]>] [-Keep] [-NoRecurse] [<CommonParameters>]

Receive-Job [-Id] <Int32[]> [-Keep] [-NoRecurse] [<CommonParameters>]

Description

The Receive-Job cmdlet gets the results of Windows Powershell background jobs. Use Receive-Job to get the results of jobs started by using the Start-Job cmdlet or the AsJob parameter of any cmdlet. You can get the results of all jobs or identify jobs by their name, ID, instance ID, computer name, location, or session, or by submitting a job object.

When you start a Windows PowerShell background job, the job starts, but the results do not appear immediately. Instead, the command returns an object that represents the background job. The job object contains useful information about the job, but it does not contain the results. This method allows you to continue working in the session while the job runs. For more information about background jobs in Windows PowerShell, see about_Jobs.

To get the results of the command, use the Receive-Job cmdlet. Receive-Job gets the results that have been generated by the time that the Receive-Job command is submitted. If the results are not yet complete, you can run additional Receive-Job commands to get the remaining results.

By default, job results are deleted from the system when you receive them, but you can use the Keep parameter to save the results so that you can receive them again. To delete the job results, receive them again (without the Keep parameter), close the session, or use the Remove-Job cmdlet to delete the job from the session.

Parameters

-ComputerName <string[]>

Gets the results of jobs that were run on the specified computers. Enter the computer names. The default is all jobs in the current session.

This parameter selects from among the job results that are stored on the local computer. It does not get data from remote computers. To get job results that are stored on remote computers, use the Invoke-Command cmdlet to run a Receive-Job command remotely.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Id <Int32[]>

Gets the results of jobs with the specified IDs. The default is all jobs in the current session.

The ID is an integer that uniquely identifies the job within the current session. It is easier to remember and type than the instance ID, but it is unique only within the current session. You can type one or more IDs (separated by commas). To find the ID of a job, type "Get-Job" without parameters.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InstanceId <Guid[]>

Gets the results of jobs with the specified instance IDs. The default is all jobs in the current session.

An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use the Get-Job cmdlet.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Job <Job[]>

Specifies the job for which results are being retrieved. This parameter is required in a Receive-Job command. Enter a variable that contains the job or a command that gets the job. You can also pipe a job object to Receive-Job.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Keep

Saves the job results in the system, even after you have received them. By default, the job results are deleted when they are retrieved.

To delete the results, use Receive-Job to receive them again without the Keep parameter, close the session, or use the Remove-Job cmdlet to delete the job from the session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Location <string[]>

Gets only the results of jobs with the specified location. The default is all jobs in the current session.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Gets the results of jobs with the specified friendly name. The default is all jobs in the current session.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-NoRecurse

Gets results only from the specified job. By default, Receive-Job also gets the results of all child jobs of the specified job.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Session <PSSession[]>

Gets the results of jobs that were run in the specified Windows Powershell session (PSSession). Enter a variable that contains the PSSession or a command that gets the PSSession, such as a Get-PSSession command. The default is all jobs in the current session.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.Job You can pipe job objects to Receive-Job.
Outputs | PSObject Receive-Job returns the results of the commands in the job.

Example 1

C:\PS>$job = start-job -scriptblock {get-process}

C:\PS> receive-job -job $job

These commands use the Job parameter to get the results of a particular job. The first command uses the Start-Job cmdlet to start a job that runs a "Get-Process" command. The command uses the assignment operator (=) to save the resulting job object in the $job variable.

The second command uses the Receive-Job cmdlet to get the results of the job. It uses the Job parameter to specify the job.

Example 2

C:\PS>$job = start-job -scriptblock {get-process}

C:\PS> $job | receive-job

This example is the same as Example 2, except that the command uses a pipeline operator (|) to send the job object to Receive-Job. As a result, the command does not need a Job parameter to specify the job.

Example 3

C:\PS>$j = invoke-command -computername Server01, Server02, Server03 -scriptblock {get-service} -AsJob

C:\PS> $j.childjobs

Id   Name     State      HasMoreData   Location       Command
--   ----     -----      -----------   --------       -------
2    Job2     Completed  True          Server01       get-service
3    Job3     Completed  True          Server02       get-service
4    Job4     Completed  True          Server03       get-service

C:\PS> receive-job -name Job3  -keep

Status  Name        DisplayName                        PSComputerName
------  ----------- -----------                        --------------
Running AeLookupSvc Application Experience             Server02
Stopped ALG         Application Layer Gateway Service  Server02
Running Appinfo     Application Information            Server02
Running AppMgmt     Application Management             Server02

Description
-----------
These commands use the Name parameter of Receive-Job to get the results of one of several background jobs run on remote computers.

The first command uses the Invoke-Command cmdlet to start a background job that runs a Get-Service command on three remote computers. The command uses the AsJob parameter to run the command as a background job. The command saves the resulting job object in the $j variable.

When you use the AsJob parameter of Invoke-Command to start a job, the job object is created on the local computer, even though the job runs on the remote computers. As a result, you use local commands to manage the job.

Also, when you use AsJob, Windows PowerShell returns one job object that contains a child job for each job that was started. In this case, the job object contains three child jobs, one for each job on each remote computer.

The second command uses the dot method to display the value of the ChildJobs property of the job object in $j. The display shows that the command created three child jobs, one for the job on each remote computer.

The third command uses the Receive-Job cmdlet to get the results of the Job3 child job that ran on the Server02 computer. It uses the Name parameter to specify the name of the child job and the Keep parameter to save the job results even after they are received.

Example 4

C:\PS>$s = new-pssession -computername Server01, Server02, Server03

C:\PS> $j = invoke-command -session $s -scriptblock {start-job -scriptblock {get-eventlog -logname system}}

C:\PS> $j

Id   Name     State      HasMoreData   Location   Command
--   ----     -----      -----------   --------   -------
1    Job1     Completed  True          Localhost  get-eventlog system
2    Job2     Completed  True          Localhost  get-eventlog system
3    Job3     Completed  True          Localhost  get-eventlog system

C:\PS> $results = invoke-command -session $s -scriptblock {param($j) receive-job -job $j} -ArgumentList $j

Description
-----------
This example shows how to get the results of background jobs run on three remote computers.

The first command uses the New-PSSession cmdlet to create three PSSessions, one on each of the servers specified in the command. It saves the PSSessions in the $s variable.

The second command uses the Invoke-Command cmdlet to run a Start-Job command in each of the PSSessions in the $s variable. The job runs a Get-Eventlog command that gets the events in the System log. The command saves the results in the $j variable.

Because the command used Invoke-Command to run the Start-Job command, the command actually started three independent jobs on each of the three computers. As a result, the command returned three job objects representing three jobs run locally on three different computers.

The third command displays the three job objects in $j.

The fourth command uses Invoke-Command to run a Receive-Job command in each of the PSSessions in $s and save the results in the $results variable.

Because $j is a local variable, the script block uses the "param" keyword to declare the variables in the command and the ArgumentList parameter to supply the value of $j.

See Also

  • about_Jobs
  • about_Job_Details
  • about_Remote_Jobs
  • Start-Job
  • Get-Job
  • Wait-Job
  • Stop-Job
  • Remove-Job
  • Invoke-Command


Register-EngineEvent

Subscribes to events that are generated by the Windows PowerShell engine and by the New-Event cmdlet.

Syntax

Register-EngineEvent [-SourceIdentifier] <string> [[-Action] <scriptblock>] [-Forward] [-MessageData <psobject>] [-SupportEvent] [<CommonParameters>]

Description

The Register-EngineEvent cmdlet subscribes to events that are generated by the Windows PowerShell engine and the New-Event cmdlet. Use the SourceIdentifier parameter to specify the event.

You can use this cmdlet to subscribe to the "Exiting" engine event and events generated by the New-Event cmdlet. These events are automatically added to your event queue in your session without subscribing. However, subscribing lets you forward the events, specify an action to respond to the events, and cancel the subscription.

When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet.

When you subscribe to a event, an event subcriber is added to your session. To get the event subscribers in the session, use the Get-EventSubscriber cmdlet. To cancel the subscription, use the Unregister-Event cmdlet, which deletes the event subscriber from the session.

Parameters

-Action <scriptblock>

Specifies commands to handle the events. The commands in the Action run when an event is raised, instead of sending the event to the event queue. Enclose the commands in braces ( { } ) to create a script block.

The value of the Action parameter can include the $Event, $EventSubscriber, $Sender, $SourceEventArgs, and $SourceArgs automatic variables, which provide information about the event to the Action script block. For more information, see about_Automatic_Variables.

When you specify an action, Register-EngineEvent returns an event job object that represents that action. You can use the Job cmdlets to manage the event job.

Required? | false
Position? | 102
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Forward

Sends events for this subscription to the session on the local computer. Use this parameter when you are registering for events on a remote computer or in a remote session.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MessageData <psobject>

Specifies additional data associated with the event. The value of this parameter appears in the MessageData property of the event object.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SourceIdentifier <string>

Specifies the source identifier of the event to which you are subscribing. The source identifier must be unique in the current session. This parameter is required.

The value of this parameter appears in the value of the SourceIdentifier property of the subscriber object and of all event objects associated with this subscription.

Required? | true
Position? | 101
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SupportEvent

Hides the event subscription. Use this parameter when the current subscription is part of a more complex event registration mechanism and it should not be discovered independently.

To view or cancel a subscription that was created with the SupportEvent parameter, use the Force parameter of the Get-EventSubscriber and Unregister-Event cmdlets.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to Register-EngineEvent.
Outputs | System.Management.Automation.PSEventJob (with -Action); otherwise none. If you use the Action parameter, Register-EngineEvent returns a System.Management.Automation.PSEventJob object. Otherwise, it does not generate any output.

Notes

Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

Example 1

C:\PS>$s = new-pssession -computername Server01, Server02

C:\PS> invoke-command -session $s { Register-EngineEvent -sourceIdentifier ([System.Management.Automation.PsEngineEvent]::Exiting) -forward }

This command registers for a Windows PowerShell engine event on two remote computers.

The first command creates a PSSession on each of the remote computers.

The second command uses the Invoke-Command cmdlet to run the Register-EngineEvent command in the remote sessions.

The Register-EngineEvent command uses the SourceIdentifier parameter to identify the event. It uses the Forward parameter to forward the events from the remote session to the local session.

Example 2

C:\PS>$j = register-engineEvent -sourceIdentifier PowerShell.ProcessCreated -action { $processName | add-content processLog.txt }

C:\PS> get-event

C:\PS> $results = $j | receive-job

C:\PS> unregister-event PowerShell.ProcessCreated

This command shows how to use the Job cmdlets to manage the event job object that Register-EngineEvent returns when you use the Action parameter.

An event job is managed just like any other Windows PowerShell job. For more information, see about_jobs. In this example, the Receive-Job cmdlet is used to get the results of the job.

To delete the job from the session, use Remove-Job. To cancel your event subscription, use the Unregister-Event cmdlet. To delete the events in the event queue, use Remove-Event.

See Also

  • Register-ObjectEvent
  • Register-WmiEvent
  • Unregister-Event
  • Get-Event
  • New-Event
  • Remove-Event
  • Wait-Event
  • Get-Job
  • Receive-Job
  • Remove-Job
  • Wait-Job


Register-ObjectEvent

Subscribes to the events that are generated by a Microsoft .NET Framework object.

Syntax

Register-ObjectEvent [-InputObject] <psobject> [-EventName] <string> [[-SourceIdentifier] <string>] [[-Action] <scriptblock>] [-Forward] [-MessageData <psobject>] [-SupportEvent] [<CommonParameters>]

Description

The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET Framework objects on the local computer or on a remote computer.

When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet.

You can use the parameters of Register-ObjectEvent to specify property values of the events that can help you to identify the event in the queue. You can also use the Action parameter to specify actions to take when a subscribed event is raised and the Forward parameter to send remote events to the event queue in the local session.

When you subscribe to an event, an event subcriber is added to your session. To get the event subscribers in the session, use the Get-EventSubscriber cmdlet. To cancel the subscription, use the Unregister-Event cmdlet, which deletes the event subscriber from the session.

Parameters

-Action <scriptblock>

Specifies commands to handle the events. The commands in the Action run when an event is raised, instead of sending the event to the event queue. Enclose the commands in braces ( { } ) to create a script block.

The value of the Action parameter can include the $Event, $EventSubscriber, $Sender, $SourceEventArgs, and $SourceArgs automatic variables, which provide information about the event to the Action script block. For more information, see about_Automatic_Variables.

When you specify an action, Register-ObjectEvent returns an event job object that represents that action. You can use the Job cmdlets to manage the event job.

Required? | false
Position? | 102
Default Value | None.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-EventName <string>

Specifies the event to which you are subscribing. Enter the event name. This parameter is required.

The value of this parameter is not a name that you select for the event subscription. It is the name of an event that the .NET Framework object exposes. For example, the ManagementEventWatcher class has events named "EventArrived" and "Stopped." To find the event name of an event, use the Get-Member cmdlet.

Required? | true
Position? | 2
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Forward

Sends events for this subscription to a remote session. Use this parameter when you are registering for events on a remote computer or in a remote session.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the .NET Framework object that generates the events. Enter a variable that contains the object, or type a command or expression that gets the object. This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MessageData <psobject>

Specifies any additional data to be associated with this event subscription. The value of this parameter appears in the MessageData property of all events associated with this subscription.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SourceIdentifier <string>

Specifies a name that you select for the subscription. The name that you select must be unique in the current session. The default value is the GUID that Windows PowerShell assigns.

The value of this parameter appears in the value of the SourceIdentifier property of the subcriber object and of all event objects associated with this subscription.

Required? | false
Position? | 101
Default Value | GUID
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SupportEvent

Hides the event subscription. Use this parameter when the current subscription is part of a more complex event registration mechanism and it should not be discovered independently.

To view or cancel a subscription that was created with the SupportEvent parameter, use the Force parameter of the Get-EventSubscriber and Unregister-Event cmdlets.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Register-ObjectEvent.
Outputs | None This cmdlet does not generate any output.

Notes

Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

Example 1

C:\PS>$query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'"

C:\PS> $processWatcher = New-Object System.Management.ManagementEventWatcher $query

C:\PS> register-objectEvent -inputObject $processWatcher -eventName "EventArrived"

This example subscribes to events generated when a new process starts.

The command uses the ManagementEventWatcher object to get EventArrived events. A query object specifies that the events are instance creation events for the Win32_Process class.

Example 2

C:\PS>$query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'"

C:\PS> $processWatcher = New-Object System.Management.ManagementEventWatcher $query

C:\PS> $action = { New-Event "PowerShell.ProcessCreated" -Sender $sender -EventArguments $SourceEventArgs.NewEvent.TargetInstance }

C:\PS> register-objectEvent -inputObject $processWatcher -eventName "EventArrived" -action $action

Id    Name            State      HasMoreData     Location             Command
--    ----            -----      -----------     --------             -------
2     422cfe5a-65e... Running    True                                 New-Event "PowerShe...

Description
-----------
This example shows how to specify an action to respond to an event. When you specify an action, events that are raised are not added to the event queue. Instead, the action responds to the event.

In this example, when an instance creation event is raised indicating that a new process is started, a new ProcessCreated event is raised.

The action uses the $Sender and $SourceEventArgs automatic variables which are populated only for event actions.

The Register-ObjectEvent command returns a job object that represents the action, which runs as a background job. You can use the Job cmdlets, such as Get-Job and Receive-Job, to manage the background job.

For more information, see about_Jobs.

Example 3

C:\PS>$s = new-pssession -computername Server01, Server02

C:\PS> invoke-command -session $s -filepath ProcessCreationEvent.ps1

C:\PS> invoke-command -session $s { get-event }

# ProcessCreationEvent.ps1

function Enable-ProcessCreationEvent
{
   $query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", `
       (New-Object TimeSpan 0,0,1), `
       "TargetInstance isa 'Win32_Process'"
   $processWatcher = New-Object System.Management.ManagementEventWatcher $query

   $identifier = "WMI.ProcessCreated"
   Register-ObjectEvent -input $processWatcher -eventName "EventArrived" `
      -sourceIdentifier $identifier -messageData "Test" -forward
   }
}

EnableProcessCreationEvent

Description
-----------
This example shows how to subscribe to object events on remote computers.

The first command creates PSSessions on two remote computers and saves them in the $s variable.

The second command uses the FilePath parameter of the Invoke-Command cmdlet to run the ProcessCreationEvent.ps1 script in the each of the PSSessions in $s.

The script includes a Register-ObjectEvent command that subscribes to instance creation events on the Win32_Process object through the ManagementEventWatcher object and its EventArrived event.

Example 4

C:\PS>$timer  = New-Object Timers.Timer

C:\PS> $timer.Interval = 500

C:\PS> $job = Register-ObjectEvent -inputObject $timer -eventName Elapsed -sourceIdentifier Timer.Random -Action {$random = Get-Random -Min 0 -Max 100}

C:\PS> $job.gettype().fullname
System.Management.Automation.PSEventJob

C:\PS> $job | format-list -property *

State         : Running
Module        : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0
StatusMessage :
HasMoreData   : True
Location      :
Command       : $random = Get-Random -Min 0 -Max 100
JobStateInfo  : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : 88944290-133d-4b44-8752-f901bd8012e2
Id            : 1
Name          : Timer.Random
ChildJobs     : {}
...

C:\PS> $timer.Enabled = $true

C:\PS> & $job.module {$random}
60

C:\PS> & $job.module {$random}
47

Description
-----------
This example shows how to use the dynamic module in the PSEventJob object that is created when you include an Action in a event registration.

The first command uses the New-Object cmdlet to create a timer object. The second command sets the interval of the timer to 500 (milliseconds).

The third command uses the Register-ObjectEvent cmdlet to register the Elapsed event of the timer object. The command includes an action that handles the event. Whenever the timer interval elapses, an event is raised and the commands in the action run. In this case, the Get-Random cmdlet generates a random number between 0 and 100 and saves it in the $random variable.

When you use an Action parameter in a Register-ObjectEvent command, the command returns a PSEventJob object that represents the action. The command saves the job object in the $job variable.

The PSEventJob object that the Register-ObjectEvent cmdlet returns is also available in the Action property of the event subscriber. For more information, see Get-EventSubscriber.

The fourth command shows that the $job variable contains a PSEventJob object. The fifth command uses the Format-List cmdlet to display all of the properties of the PSEventJob object in a list.

The PSEventJob has a Module property that contains a dynamic script module that implements the action.

The sixth command enables the timer.

The remaining commands use the call operator (&) to invoke the command in the module and display the value of the $random variable. You can use the call operator to invoke any command in a module, including commands that are not exported. In this case, the commands show the random number that is being generated when the Elapsed event occurs.

For more information about modules, see about_Modules.

See Also

  • Register-EngineEvent
  • Register-WmiEvent
  • Unregister-Event
  • Get-Event
  • New-Event
  • Remove-Event
  • Wait-Event


Register-PSSessionConfiguration

Creates and registers a new session configuration.

Syntax

Register-PSSessionConfiguration [-AssemblyName] <string> [-ConfigurationTypeName] <string> [-ApplicationBase <string>] [-Name] <string> [-Force] [-MaximumReceivedDataSizePerCommandMB <double>] [-MaximumReceivedObjectSizeMB <double>] [-NoServiceRestart] [-ProcessorArchitecture <string>] [-SecurityDescriptorSDDL <string>] [-ShowSecurityDescriptorUI] [-StartupScript <string>] [-ThreadApartmentState {<STA> | <MTA> | <Unknown>}] [-ThreadOptions {<Default> | <UseNewThread> | <ReuseThread> | <UseCurrentThread>}] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Register-PSSessionConfiguration cmdlet creates and registers a new session configuration on the local computer. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users.

Every Windows PowerShell remote session uses a session configuration. When users create a session that connects to the computer, they can select a configuration or use the default configurations that are registered when you enable Windows PowerShell remoting. Users can also set the $PSSessionConfigurationName preference variable, which specifies a default configuration for sessions created in the current session.

The session configuration configures the environment for the session. You can define the configuration by using an assembly that implements a new configuration class and by using a script that runs in the session. The configuration can determine which commands are available in the session, and it can include settings that protect the computer, such as those that limit the amount of data that the session can receive remotely in a single object or command. You can also specify a security descriptor that determines the permissions that are required to use the configuration.

Parameters

-ApplicationBase <string>

Specifies the path to the assembly file (*.dll) that is specified in the value of the AssemblyName parameter. Use this parameter when the value of the AssemblyName parameter does not include a path. The default is the current directory.

Required? | false
Position? | named
Default Value | Current directory
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AssemblyName <string>

Specifies the name of an assembly file (*.dll) in which the configuration type is defined. You can specify the path to the .dll in this parameter or in the value of the ApplicationBase parameter.

This parameter is required when the ConfigurationTypeName parameter is specified.

Required? | true
Position? | 2
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ConfigurationTypeName <string>

Specifies the fully qualified name of the Microsoft .NET Framework type that is used for this configuration. The type that you specify must implement the System.Management.Automation.Remoting.PSSessionConfiguration class.

To specify the assembly file (.dll) that implements the configuration type, use the AssemblyName and AssemblyBase parameters.

Creating a type allows you to control more aspects of the session configuration, such as exposing or hiding certain parameters of cmdlets, or setting data size and object size limits that users cannot override.

If you omit this parameter, the DefaultRemotePowerShellConfiguration class is used for the session configuration.

Required? | true
Position? | 3
Default Value | System.Management.Automation.Remoting.PSSessionConfiguration
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Suppresses all users prompts and restarts the WinRM service without prompting. Restarting the service makes the configuration change effective.

To prevent a restart and suppress the restart prompt, use the NoServiceRestart parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MaximumReceivedDataSizePerCommandMB <double>

Limits the amount of data that can be sent to this computer in any single remote command. Enter the data size in megabytes (MB). The default is 50 MB.

If a data size limit is defined in the configuration type that is specified in the ConfigurationTypeName parameter, the limit in the configuration type is used and the value of this parameter is ignored.

Required? | false
Position? | named
Default Value | 50
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MaximumReceivedObjectSizeMB <double>

Limits the amount of data that can be sent to this computer in any single object. Enter the data size in megabytes (MB). The default is 10 MB.

If an object size limit is defined in the configuration type that is specified in the ConfigurationTypeName parameter, the limit in the configuration type is used and the value of this parameter is ignored.

Required? | false
Position? | named
Default Value | 10
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies a name for the session configuration. This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoServiceRestart

Does not restart the WinRM service, and suppresses the prompt to restart the service.

By default, when you enter a Register-PSSessionConfiguration command, you are prompted to restart the WinRM service to make the new session configuration effective. Until the WinRM service is restarted, the new session configuration is not effective.

To restart the WinRM service without prompting, use the Force parameter. To restart the WinRM service manually, use the Restart-Service cmdlet.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ProcessorArchitecture <string>

Specifies a processor architecture for the configuration. This value determines whether a 32-bit or 64-bit version of the process that hosts Windows PowerShell is started when the configuration is used. Valid values are x86, AMD64, and IA64.

The default is determined by the processor architecture of the computer that hosts the session configuration.

Required? | false
Position? | named
Default Value | The processor architecture of the host computer.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SecurityDescriptorSDDL <string>

Specifies a Security Descriptor Definition Language (SDDL) string for the configuration.

This string determines the permissions that are required to use the new session configuration. To use a session configuration in a session, users must have at least "Execute(Invoke)" permission for the configuration.

If the security descriptor is complex, consider using the ShowSecurityDescriptorUI parameter instead of this parameter. You cannot use both parameters in the same command.

If you omit this parameter, the root SDDL for the WinRM service is used for this configuration. To view or change the root SDDL, use the WS-Management Provider. For example "Get-Item wsman:\localhost\service\rootSDDL". For more information about the WS-Management Provider, type "Get-Help wsman".

Required? | false
Position? | named
Default Value | The value of the root SDDL
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ShowSecurityDescriptorUI

Displays a property sheet that helps you to create the SDDL for the session configuration. The property sheet appears after you enter the Register-PSSessionConfiguration command and then restart the WinRM service.

When setting the permissions for the configuration, remember that users must have at least "Execute(Invoke)" permission to use the session configuration in a session.

You cannot use the SecurityDescriptorSDDL parameter and this parameter in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-StartupScript <string>

Specifies the fully qualified path to a Windows PowerShell script. The specified script runs in the new session that uses the session configuration.

You can use the script to further configure the session. If the script generates an error (even a non-terminating error), the session is not created and the user's New-PSSession command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThreadApartmentState <ApartmentState>

Determines the apartment state of the threads in the session. Valid values are STA, MTA, and Unknown. Unknown is the default.

Required? | false
Position? | named
Default Value | Unknown
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThreadOptions <PSThreadOptions>

Defines how threads are created and used when a command is executed in the session. Valid values are Default, ReuseThread, UseCurrentThread, and UseNewThread. UseCurrentThread is the default.

Required? | false
Position? | named
Default Value | UseCurrentThread
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | Microsoft.WSMan.Management.WSManConfigContainerElement

Notes

To run this cmdlet on Windows Vista, Windows Server 2008, and later versions of Windows, you must start Windows PowerShell with the "Run as administrator" option.

This cmdlet generates XML that represents a Web Services for Management (WS-Management) plug-in configuration and sends the XML to WS-Management, which registers the plug-in on the local computer ("new-item wsman:\localhost\plugin").

Example 1

C:\PS>register-pssessionConfiguration -name NewShell -applicationBase c:\MyShells\ -assemblyName MyShell.dll -configurationTypeName MyClass

This command registers the NewShell session configuration. It uses the ApplicationName and ApplicationBase parameters to specify the location of the MyShell.dll file, which specifies the cmdlets and providers in the session configuration. It also uses the ConfigurationTypeName parameter to specify a new class that further configures the session.

To use this configuration, users would type "new-pssession -configurationname newshell".

Example 2

C:\PS>register-pssessionConfiguration -name MaintenanceShell -startupScript c:\ps-test\Maintenance.ps1

This command registers the MaintenanceShell configuration on the local computer. The command uses the StartupScript parameter to specify the Maintenance.ps1 script.

When a user uses a New-PSSession command and selects the MaintenanceShell configuration, the Maintenance.ps1 script runs in the new session. The script can configure the session, including importing modules, adding Windows PowerShell snap-ins, and setting the execution policy for the session. If the script generates any errors, including non-terminating errors, the New-PSSession command fails.

Example 3

C:\PS>$sddl = "O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;FA;SA;GWGX;;WD)"

C:\PS> register-pssessionconfiguration -name AdminShell -securityDescriptorSDDL $sddl -maximumReceivedObjectSizeMB 20 -startupScript c:\scripts\AdminShell.ps1

This example registers the AdminShell session configuration.

The first command saves a custom SDDL in the $sddl variable.

The second command registers the new shell. The command uses the SecurityDescritorSDDL parameter to specify the SDDL in the value of the $sddl variable and the MaximumReceivedObjectSizeMB parameter to increase the object size limit. It also uses the StartupScript parameter to specify a script that configures the session.

As an alternative to using the SecurityDescriptorSDDL parameter, you can use the ShowSecurityDescriptorUI parameter, which displays a property sheet that you can use to set permissions for the session configuration. When you click "OK" in the property sheet, the tool generates an SDDL for the session configuration.

Example 4

C:\PS>$s = register-pssessionConfiguration -name MaintenanceShell -startupScript c:\ps-test\Maintenance.ps1

C:\PS> $s

   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin

Name                      Type                 Keys
----                      ----                 ----
MaintenanceShell          Container            {Name=MaintenanceShell}

C:\PS> $s.getType().fullname
TypeName: Microsoft.WSMan.Management.WSManConfigContainerElement

C:\PS> $s | format-list -property *

PSPath            : Microsoft.WSMan.Management\WSMan::localhost\Plugin\MaintenanceShell
PSParentPath      : Microsoft.WSMan.Management\WSMan::localhost\Plugin
PSChildName       : MaintenanceShell
PSDrive           : WSMan
PSProvider        : Microsoft.WSMan.Management\WSMan
PSIsContainer     : True
Keys              : {Name=MaintenanceShell}
Name              : MaintenanceShell
TypeNameOfElement : Container

C:\PS> dir wsman:\localhost\plugin

Name                      Type                 Keys
----                      ----                 ----
MaintenanceShell          Container            {Name=MaintenanceShell}
microsoft.powershell      Container            {Name=microsoft.powershell}
microsoft.powershell32    Container            {Name=microsoft.powershell32}

Description
-----------
This example shows that a Register-PSSessionConfiguration command returns a WSManConfigContainerElement. It also shows how to find the container elements in the WSMan: drive.

The first command uses the Register-PSSessionConfiguration cmdlet to register the MaintenanceShell configuration. It saves the object that the cmdlet returns in the $s variable.

The second command displays the contents of the $s variable.

The third command uses the GetType method and its FullName property to display the type name of the object that Register-PSSessionConfiguration returns.

The fourth command uses the Format-List cmdlet to display all the properties of the object that Register-PSSessionConfiguration returns in a list. The PSPath property shows that the object is stored in a directory of the WSMan: drive.

The fifth command uses the Get-ChildItem cmdlet to display the items in the WSMan:\LocalHost\PlugIn path. These include the new MaintenanceShell configuration and the two default configurations that come with Windows PowerShell.

Example 5

C:\PS>register-pssessionconfiguration -name WithProfile -startupScript add-profile.ps1

# Add-Profile.ps1

. c:\users\admin01\documents\windowspowershell\profile.ps1

Description
-----------
This command creates and registers the WithProfile session configuration on the local computer. The command uses the StartupScript parameter to direct Windows PowerShell to run the specified script in any session that uses the session configuration.

The content of the specified script, Add-Profile.ps1, is also displayed. The script contains a single command that uses dot sourcing to run the user's CurrentUserAllHosts profile in the current scope of the session.

For more information about profiles, see about_Profiles. For more information about dot sourcing, see about_Scopes.

See Also

  • about_Session_Configurations
  • Disable-PSSessionConfiguration
  • Enable-PSSessionConfiguration
  • Get-PSSessionConfiguration
  • Set-PSSessionConfiguration
  • Unregister-PSSessionConfiguration
  • WS-Management Provider


Register-WmiEvent

Subscribes to a Windows Management Instrumentation (WMI) event.

Syntax

Register-WmiEvent [-Class] <string> [[-SourceIdentifier] <string>] [[-Action] <scriptblock>] [-ComputerName <string>] [-Credential <PSCredential>] [-Forward] [-MessageData <psobject>] [-Namespace <string>] [-SupportEvent] [-Timeout <Int64>] [<CommonParameters>]

Register-WmiEvent [-Query] <string> [[-SourceIdentifier] <string>] [[-Action] <scriptblock>] [-ComputerName <string>] [-Credential <PSCredential>] [-Forward] [-MessageData <psobject>] [-Namespace <string>] [-SupportEvent] [-Timeout <Int64>] [<CommonParameters>]

Description

The Register-WmiEvent cmdlet subscribes to WMI events on the local computer or on a remote computer.

When the subscribed WMI event is raised, it is added to the event queue in your local session even if the event occurs on a remote computer. To get events in the event queue, use the Get-Event cmdlet.

You can use the parameters of Register-WmiEvent to subscribe to events on remote computers and to specify the property values of the events that can help you to identify the event in the queue. You can also use the Action parameter to specify actions to take when a subscribed event is raised.

When you subscribe to an event, an event subscriber is added to your session. To get the event subscribers in the session, use the Get-EventSubscriber cmdlet. To cancel the subscription, use the Unregister-Event cmdlet, which deletes the event subscriber from the session.

Parameters

-Action <scriptblock>

Specifies commands that handle the events. The commands in the Action parameter run when an event is raised instead of sending the event to the event queue. Enclose the commands in braces ( { } ) to create a script block.

The value of the Action parameter can include the $Event, $EventSubscriber, $Sender, $SourceEventArgs, and $SourceArgs automatic variables, which provide information about the event to the Action script block. For more information, see about_Automatic_Variables.

When you specify an action, Register-WmiEvent returns an event job object that represents that action. You can use the cmdlets that contain the Job noun (the Job cmdlets) to manage the event job.

Required? | false
Position? | 102
Default Value | The event is added to the event queue.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Class <string>

Specifies the event to which you are subscribing. Enter the WMI class that generates the events. A Class or Query parameter is required in every command.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies a remote computer. The default is the local computer. Enter a NetBIOS name, an IP address, or a fully qualified domain name.

Required? | false
Position? | named
Default Value | Local computer
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one from the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | The credentials of the current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Forward

Sends events for this subscription to the session on the local computer. Use this parameter when you are registering for events on a remote computer or in a remote session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MessageData <psobject>

Specifies any additional data to be associated with this event subscription. The value of this parameter appears in the MessageData property of all events associated with this subscription.

Required? | false
Position? | named
Default Value | None. The MessageData property is NULL.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Namespace <string>

Specifies the namespace of the WMI class.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Query <string>

Specifies a query in WMI Query Language (WQL) that identifies the WMI event class, such as "select * from __InstanceDeletionEvent".

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SourceIdentifier <string>

Specifies a name that you select for the subscription. The name that you select must be unique in the current session. The default value is the GUID that Windows PowerShell assigns.

The value of this parameter appears in the value of the SourceIdentifier property of the subscriber object and of all event objects associated with this subscription.

Required? | false
Position? | 101
Default Value | GUID
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SupportEvent

Hides the event subscription. Use this parameter when the current subscription is part of a more complex event registration mechanism and it should not be discovered independently.

To view or cancel a subscription that was created with the SupportEvent parameter, use the Force parameter of the Get-EventSubscriber and Unregister-Event cmdlets.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Timeout <Int64>

Determines how long Windows PowerShell waits for this command to complete.

The default value, 0 (zero), means that there is no time-out, and it causes Windows PowerShell to wait indefinitely.

Required? | false
Position? | named
Default Value | 0
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to Register-WmiEvent.
Outputs | None This cmdlet does not generate any output.

Notes

To use this cmdlet in Windows Vista or a later version of Windows, start Windows PowerShell with the "Run as administrator" option.

Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

Example 1

C:\PS>register-wmiEvent -class 'Win32_ProcessStartTrace' -sourceIdentifier "ProcessStarted"

This command subscribes to the events generated by the Win32_ProcessStartTrace class. This class raises an event whenever a process starts.

Example 2

C:\PS>register-wmiEvent -query "select * from __instancecreationevent within 5 where targetinstance isa 'win32_process'" -sourceIdentifier "WMIProcess" -messageData "Test 01" -timeout 500

This command uses a query to subscribe to Win32_process instance creation events.

Example 3

C:\PS>$action = { get-history | where { $_.commandline -like "*start-process*" } | export-cliXml "commandHistory.clixml" }

C:\PS> register-wmiEvent -class 'Win32_ProcessStartTrace' -sourceIdentifier "ProcessStarted" -action $action

Id    Name            State      HasMoreData   Location  Command
--    ----            -----      -----------   --------  -------
1     ProcessStarted  NotStarted False                   get-history | where {...

Description
-----------
This example shows how to use an action to respond to an event. In this case, when a process starts, any Start-Process commands in the current session are written to an XML file.

When you use the Action parameter, Register-WmiEvent returns a background job that represents the event action. You can use the Job cmdlets, such as Get-Job and Receive-Job, to manage the event job.

For more information, see about_Jobs.

Example 4

C:\PS>register-wmiEvent -class 'Win32_ProcessStartTrace' -sourceIdentifier "Start" -computername Server01

C:\PS> get-event -sourceIdentifier "Start"

This example registers for events on the Server01 remote computer.

WMI returns the events to the local computer and stores them in the event queue in the current session. To retrieve the events, run a local Get-Event command.

See Also

  • Register-ObjectEvent
  • Register-EngineEvent
  • Unregister-Event
  • Get-Event
  • New-Event
  • Remove-Event
  • Wait-Event


Remove-Computer

Remove the local computer from a workgroup or domain.

Syntax

Remove-Computer [[-Credential] <PSCredential>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-Computer cmdlet removes the local computer from its current workgroup or domain.

When you remove a computer from a domain, Remove-Computer also disables the computer's domain account.

When the computer is in a domain, you must provide credentials, even when they are the credentials of the current user, and you must restart the computer to make the change effective.

To get the results of the command, use the Verbose and PassThru parameters.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

To remove a computer from a domain, you must use the Credential parameter, even when you are using the credentials of the current user.

Required? | false
Position? | 2
Default Value | The credentials of the current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns the results of the command. Otherwise, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet
Outputs | Microsoft.PowerShell.Commands.ComputerChangeInfo When you use the PassThru parameter, Remove-Computer returns a ComputerChangeInfo object. Otherwise, this cmdlet does not generate any output.

Example 1

C:\PS>remove-computer

This command removes the computer from a workgroup.

Example 2

C:\PS>remove-computer -credential domain01\admin01 -passthru -verbose; restart-computer

These commands remove the local computer from the domain to which it is joined.

The first command removes the computer from the domain. The command uses the Credential parameter to supply the credentials of a domain administrator. It uses the PassThru parameter and the Verbose common parameter to display information about the success or failure of the command.

The second command uses the Restart-Computer cmdlet to restart the computer, which is required to complete the remove operation.

The semi-colon (;) separates the two commands.

See Also

  • Add-Computer
  • Checkpoint-Computer
  • Remove-Computer
  • Restart-Computer
  • Restore-Computer
  • Stop-Computer
  • Test-Connection


Remove-Event

Deletes events from the event queue.

Syntax

Remove-Event [-EventIdentifier] <int> [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-Event [-SourceIdentifier] <string> [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-Event cmdlet deletes events from the event queue in the current session.

This cmdlet deletes only the events currently in the queue. To cancel event registrations or unsubscribe, use the Unregister-Event cmdlet.

Parameters

-EventIdentifier <int>

Deletes only the event with the specified event identifier. An EventIdentifier or SourceIdentifier parameter is required in every command.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-SourceIdentifier <string>

Deletes only the events with the specified source identifier. Wildcards are not permitted. An EventIdentifier or SourceIdentifier parameter is required in every command.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSEventArgs You can pipe events from Get-Event to Remove-Event.
Outputs | None The cmdlet does not generate any output.

Notes

Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

Example 1

C:\PS>remove-event -sourceIdentifier "ProcessStarted"

This command deletes events with a source identifier of "Process Started" from the event queue.

Example 2

C:\PS>remove-event -eventIdentifier 30

This command deletes the event with an event ID of 30 from the event queue.

Example 3

C:\PS>get-event | remove-event

This command deletes all events from the event queue.

See Also

  • Register-ObjectEvent
  • Register-EngineEvent
  • Register-WmiEvent
  • Unregister-Event
  • Get-Event
  • New-Event
  • Remove-Event
  • Wait-Event


Remove-EventLog

Deletes an event log or unregisters an event source.

Syntax

Remove-EventLog [-LogName] <string[]> [[-ComputerName] <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-EventLog [[-ComputerName] <string[]>] [-Source <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-EventLog cmdlet deletes an event log file from a local or remote computer and unregisters all of its event sources for the log. You can also use this cmdlet to unregister event sources without deleting any event logs.

The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.

Parameters

-ComputerName <string[]>

Specifies a remote computer. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Remove-EventLog even if your computer is not configured to run remote commands.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LogName <string[]>

Specifies the event logs. Enter the log name (the value of the Log property; not the LogDisplayName) of one or more event logs , separated by commas. Wildcard characters are not permitted. This parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Source <string[]>

Unregisters the specified event sources. Enter the source names (not the executable name), separated by commas.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not return any output.

Notes

To use Remove-EventLog on Windows Vista and later versions of Windows, start Windows PowerShell with the "Run as administrator" option.

If you remove an event log and then re-create the log, you will not be able to register the same event sources. Applications that used the events sources to write entries to the original log will not be able to write to the new log.

When you unregister an event source for a particular log, the event source might be prevented from writing entries in other event logs.

Example 1

C:\PS>remove-eventlog -logname MyLog

This command deletes the MyLog event log from the local computer and unregisters its event sources.

Example 2

C:\PS>remove-eventlog -logname MyLog, TestLog -computername Server01, Server02, localhost

This command deletes the MyLog and TestLog event logs from the local computer ("localhost") and the Server01 and Server02 remote computers. The command also unregisters the event sources for these logs.

Example 3

C:\PS>remove-eventlog -source MyApp

This command deletes the MyApp event source from the logs on the local computer. When the command completes, the MyApp program cannot write to any event logs.

Example 4

C:\PS>get-eventlog -list

Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  15,168      0 OverwriteAsNeeded      22,923 Application
  15,168      0 OverwriteAsNeeded          53 DFS Replication
     512      7 OverwriteOlder              0 Directory Service
  15,168      7 OverwriteOlder              0 Hardware Events
     512      7 OverwriteOlder              0 Internet Explorer
  20,480      0 OverwriteAsNeeded           0 Key Management Service
  30,016      0 OverwriteAsNeeded      50,060 Security
  15,168      0 OverwriteAsNeeded      27,592 System
  15,360      0 OverwriteAsNeeded      18,355 Windows PowerShell
  15,168      7 OverwriteAsNeeded          12 ZapLog

C:\PS> remove-eventlog -logname ZapLog

C:\PS> get-eventlog -list

  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  15,168      0 OverwriteAsNeeded      22,923 Application
  15,168      0 OverwriteAsNeeded          53 DFS Replication
     512      7 OverwriteOlder              0 Directory Service
  15,168      7 OverwriteOlder              0 Hardware Events
     512      7 OverwriteOlder              0 Internet Explorer
  20,480      0 OverwriteAsNeeded           0 Key Management Service
  30,016      0 OverwriteAsNeeded      50,060 Security
  15,168      0 OverwriteAsNeeded      27,592 System
  15,360      0 OverwriteAsNeeded      18,355 Windows PowerShell

Description
-----------
These commands show how to list the event logs on a computer and verify that a Remove-EventLog command was successful.

The first command lists the event logs on the local computer.

The second command deletes the ZapLog event log.

The third command lists the event logs again. The ZapLog event log no longer appears in the list.

Example 5

C:\PS>get-wmiobject win32_nteventlogfile -filter "logfilename='TestLog'" | foreach {$_.sources}

MyApp
TestApp

C:\PS> remove-eventlog -source MyApp

C:\PS> get-wmiobject win32_nteventlogfile -filter "logfilename='TestLog'} | foreach {$_.sources}
TestApp

Description
-----------
These commands use the Get-WmiObject cmdlet to list the event sources on the local computer. You can these commands to verify the success of a command or to delete an event source.

The first command gets the event sources of the TestLog event log on the local computer. MyApp is one of the sources.

The second command uses the Source parameter of Remove-EventLog to delete the MyApp event source.

The third command is identical to the first. It shows that the MyApp event source was deleted.

See Also

  • Clear-EventLog
  • Get-EventLog
  • Limit-EventLog
  • New-EventLog
  • Remove-EventLog
  • Show-Eventlog
  • Write-EventLog
  • Get-WinEvent


Remove-Item

Deletes the specified items.

Syntax

Remove-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Recurse] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Remove-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Recurse] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Remove-Item cmdlet deletes one or more items. Because it is supported by many providers, it can delete many different types of items, including files, directories, registry keys, variables, aliases, and functions.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to remove items that cannot otherwise be changed, such as hidden or read-only files or read-only aliases or variables. The cmdlet cannot remove constant aliases or variables. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Deletes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the items being removed. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies a path to the items being removed. Wildcards are permitted. The parameter name ("-Path") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Recurse

Deletes the items in the specified locations and in all child items of the locations.

The Recurse parameter in this cmdlet does not work properly.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path (but not a literal path) to Remove-Item.
Outputs | None This cmdlet does not return any output.

Notes

You can also refer to Remove-Item by any of its built-in aliases, "del", "erase", "rmdir", "rd", "ri", or "rm". For more information, see about_Aliases.

The Remove-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>remove-item C:\Test\*.*

This command deletes all of the files with names that include a dot (.) from the C:\Test directory. Because the command specifies a dot, the command does not delete directories or files with no file name extension.

Example 2

C:\PS>remove-item * -include *.doc -exclude *1*

This command deletes from the current directory all files with a .doc file name extension and a name that does not include "1". It uses the wildcard character (*) to specify the contents of the current directory. It uses the Include and Exclude parameters to specify the files to delete.

Example 3

C:\PS>remove-item -path C:\Test\hidden-RO-file.txt -force

This command deletes a file that is both hidden and read-only. It uses the Path parameter to specify the file. It uses the Force parameter to give permission to delete it. Without Force, you cannot delete read-only or hidden files.

Example 4

C:\PS>get-childitem * -include *.csv -recurse | remove-item

This command deletes all of the CSV files in the current directory and all subdirectories recursively.

Because the Recurse parameter in this cmdlet is faulty, the command uses the Get-Childitem cmdlet to get the desired files, and it uses the pipeline operator to pass them to the Remove-Item cmdlet.

In the Get-ChildItem command, the Path parameter has a value of *, which represents the contents of the current directory. It uses the Include parameter to specify the CSV file type, and it uses the Recurse parameter to make the retrieval recursive.

If you try to specify the file type in the path, such as "-path *.csv", the cmdlet interprets the subject of the search to be a file that has no child items, and Recurse fails.

Example 5

C:\PS>remove-item hklm:\software\mycompany\OldApp -recurse

This command deletes the OldApp registry key and all of its subkeys and values. It uses the Remove-Item cmdlet to remove the key. The path is specified, but the optional parameter name (Path) is omitted.

The Recurse parameter deletes all of the contents of the OldApp key recursively. If the key contains subkeys and you omit the Recurse parameter, you are prompted to confirm that you want to delete the contents of the key.

See Also

  • about_Providers
  • Clear-Item
  • Copy-Item
  • Get-Item
  • Invoke-Item
  • Move-Item
  • New-Item
  • Remove-ItemProperty
  • Rename-Item
  • Set-Item


Remove-ItemProperty

Deletes the property and its value from an item.

Syntax

Remove-ItemProperty [-LiteralPath] <string[]> [-Name] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Remove-ItemProperty [-Path] <string[]> [-Name] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Remove-ItemProperty cmdlet deletes a property and its value from an item. You can use it to delete registry values and the data that they store.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to remove a property of an object that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see about_Providers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Deletes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of the properties to be retrieved.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the item whose properties are being removed. Wildcards are permitted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path (but not a literal path) to Remove-ItemProperty.
Outputs | None This cmdlet does not return any output.

Notes

You can also refer to Remove-ItemProperty by its built-in alias, "rp". For more information, see about_Alias.

In the Windows PowerShell Registry Provider, registry values are considered to be properties of a registry key or subkey. You can use the ItemProperty cmdlets to manage these values.

The Remove-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>remove-itemproperty -path HKLM:\Software\SmpApplication -name SmpProperty

This command deletes the SmpProperty registry value, and its data, from the SmpApplication subkey of the HKEY_LOCAL_MACHINE\Software registry key.

Because the command is issued from a file system drive (C:\PS>), it includes the fully qualified path to the SmpApplication subkey, including the drive, HKLM:, and the Software key.

It uses the Name parameter to identify the registry value that is being deleted.

Example 2

C:\PS>set-location HKCU:\Software\MyCompany\MyApp

PS HKCU:\Software\MyCompany\MyApp> remove-itemproperty -path . -Name Options -confirm

These commands delete the Options registry value, and its data, from the MyApp subkey of HKEY_CURRENT_USER\Software\MyCompany.

The first command uses the Set-Location cmdlet to change the current location to the HKEY_CURRENT_USER drive (HKCU:) and the Software\MyCompany\MyApp subkey.

The second command uses the Remove-Item cmdlet to remove the Options registry value, and its data, from the MyApp subkey. Because the Path parameter is required, the command uses a dot (.) to indicate the current location. It uses the Name parameter to specify which registry value to delete. It uses the Confirm parameter to request a user prompt before deleting the value.

Example 3

C:\PS>get-item -path HKLM:\Software\MyCompany | remove-itemproperty -name NoOfEmployees

This command deletes the NoOfEmployees registry value, and its data, from the HKLM\Software\MyCompany registry key.

The command uses the Get-Item cmdlet to get an item that represents the registry key. It uses a pipeline operator (|) to send the object to the Remove-ItemProperty cmdlet. Then, it uses the Name parameter of Remove-ItemProperty to specify the name of the registry value.

See Also

  • about_Providers
  • Clear-ItemProperty
  • Copy-ItemProperty
  • Get-ItemProperty
  • Move-ItemProperty
  • New-ItemProperty
  • Remove-Item
  • Rename-ItemProperty
  • Set-ItemProperty


Remove-Job

Deletes a Windows PowerShell background job.

Syntax

Remove-Job [-Id] <Int32[]> [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-Job [-Command <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-Job [[-InstanceId] <Guid[]>] [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-Job [-Job] <Job[]> [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-Job [[-Name] <string[]>] [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-Job [-State {<NotStarted> | <Running> | <Completed> | <Failed> | <Stopped> | <Blocked>}] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-Job cmdlet deletes Windows PowerShell background jobs that were started by using Start-Job or the AsJob parameter of any cmdlet.

You can use this cmdlet to delete all jobs or delete selected jobs based on their name, ID, instance ID, command, or state, or by passing a job object to Remove-Job. Without parameters or parameter values, Remove-Job has no effect.

Before deleting a running job, use the Stop-Job cmdlet to stop the job. If you try to delete a running job, the command fails. You can use the Force parameter of Remove-Job to delete a running job.

If you do not delete a background job, the job remains in the global job cache until you close the session in which the job was created.

Parameters

-Command <string[]>

Removes jobs that include the specified words in the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Force

Deletes the job even if the status is "Running". Without the Force parameter, Remove-Job will not delete a running job.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Id <Int32[]>

Deletes background jobs with the specified IDs.

The ID is an integer that uniquely identifies the job within the current session. It is easier to remember and type than the instance ID, but it is unique only within the current session. You can type one or more IDs (separated by commas). To find the ID of a job, type "Get-Job" without parameters.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InstanceId <Guid[]>

Deletes jobs with the specified instance IDs.

An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use Get-Job or display the job object.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Job <Job[]>

Specifies the jobs to be deleted. Enter a variable that contains the jobs or a command that gets the jobs. You can also use a pipeline operator to submit jobs to the Remove-Job cmdlet.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Deletes only the jobs with the specified friendly names. Wildcards are permitted.

Because the friendly name is not guaranteed to be unique, even within the session, use the WhatIf and Confirm parameters when deleting jobs by name.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-State <JobState>

Deletes only jobs with the specified status. Valid values are NotStarted, Running, Completed, Stopped, Failed, and Blocked. To delete jobs with a status of Running, use the Force parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.Job You can pipe a job object to Remove-Job.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>$batch = get-job -name BatchJob

C:\PS> $batch | remove-job

These commands delete a background job named BatchJob from the current session. The first command uses the Get-Job cmdlet to get an object representing the job, and then it saves the job in the $batch variable. The second command uses a pipeline operator (|) to send the job to the Remove-Job cmdlet.

This command is equivalent to using the Job parameter of Remove-Job, for example, "remove-job -job $batch".

Example 2

C:\PS>get-job | remove-job

This command deletes all of the jobs in the current session.

Example 3

C:\PS>remove-job -state NotStarted

This command deletes all jobs from the current session that have not yet been started.

Example 4

C:\PS>remove-job -name *batch -force

This command deletes all jobs with friendly names that end with "batch" from the current session, including jobs that are running.

It uses the Name parameter of Remove-Job to specify a job name pattern, and it uses the Force parameter to ensure that all jobs are removed, even those that might be in progress.

Example 5

C:\PS>$j = invoke-command -computername Server01 -scriptblock {get-process} -asJob

C:\PS> $j | remove-job

This example shows how to use the Remove-Job cmdlet to remove a job that was started on a remote computer by using the AsJob parameter of the Invoke-Command cmdlet.

The first command uses the Invoke-Command cmdlet to run a job on the Server01 computer. It uses the AsJob parameter to run the command as a background job, and it saves the resulting job object in the $j variable.

Because the command used the AsJob parameter, the job object is created on the local computer, even though the job runs on a remote computer. As a result, you use local commands to manage the job.

The second command uses the Remove-Job cmdlet to remove the job. It uses a pipeline operator (|) to send the job in $j to Remove-Job. Note that this is a local command. A remote command is not required to remove a job that was started by using the AsJob parameter.

Example 6

C:\PS>$s = new-pssession -computername Server01

C:\PS> invoke-command -session $s -scriptblock {start-job -scriptblock {get-process} -name MyJob}

C:\PS> invoke-command -session $s -scriptblock {remove-job -name MyJob}

This example shows how to remove a job that was started by using Invoke-Command to run a Start-Job command. In this case, the job object is created on the remote computer and you use remote commands to manage the job.

The first command uses the New-PSSession cmdlet to create a PSSession (a persistent connection) to the Server01 computer. A persistent connection is required when running a Start-Job command remotely. The command saves the PSSession in the $s variable.

The second command uses the Invoke-Command cmdlet to run a Start-Job command in the PSSession in $s. The job runs a Get-Process command. It uses the Name parameter of Start-Job to specify a friendly name for the job.

The third command uses the Invoke-Command cmdlet to run a Remove-Job command in the PSSession in $s. The command uses the Name parameter of Remove-Job to identify the job to be deleted.

Example 7

C:\PS>$j = start-job -script {get-process powershell}

C:\PS> $j | format-list -property *

C:\PS> remove-job -instanceID dce2ee73-f8c9-483e-bdd7-a549d8687eed

C:\PS> $j = start-job -script {get-process powershell}

C:\PS> $j | format-list -property *

HasMoreData   : False
StatusMessage :
Location      : localhost
Command       : get-process powershell
JobStateInfo  : Failed
Finished      : System.Threading.ManualResetEvent
InstanceId    : dce2ee73-f8c9-483e-bdd7-a549d8687eed
Id            : 1
Name          : Job1
ChildJobs     : {Job2}
Output        : {}
Error         : {}
Progress      : {}
Verbose       : {}
Debug         : {}
Warning       : {}
StateChanged  :

C:\PS> remove-job -instanceID dce2ee73-f8c9-483e-bdd7-a549d8687eed

Description
-----------
This example shows how to remove a job based on its instance ID.

The first command uses the Start-Job cmdlet to start a background job. The command saves the resulting job object in the $j variable.

The second command uses a pipeline operator (|) to send the job object in $j to a Format-List command. The Format-List command uses the Property parameter with a value of * (all) to display all of the properties of the job object in a list.

The job object display shows the values of the ID and InstanceID properties, along with the other properties of the object.

The third command uses a Remove-Job command to remove the job from the current session. To generate the command, you can copy and paste the InstanceID value from the object display.

To copy a value in the Windows PowerShell console, use the mouse to select the value, and then press Enter to copy it. To paste a value, right-click.

See Also

  • about_Jobs
  • about_Job_Details
  • about_Remote_Jobs
  • Start-Job
  • Get-Job
  • Receive-Job
  • Wait-Job
  • Stop-Job
  • Invoke-Command


Remove-Module

Removes modules from the current session.

Syntax

Remove-Module [-ModuleInfo] <PSModuleInfo[]> [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-Module [-Name] <string[]> [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-Module cmdlet removes the members of a module from the current session.

If the module includes an assembly (.dll), all members that are implemented by the assembly are removed, but the assembly is not unloaded.

Parameters

-Force

Removes modules even when their access mode is read-only.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ModuleInfo <PSModuleInfo[]>

Specifies the module objects to remove. Enter a variable that contains a module object (PSModuleInfo) or a command that gets a module object, such as a Get-Module command. You can also pipe module objects to Remove-Module.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of modules to remove. Wildcards are permitted. You can also pipe name strings to Remove-Module.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | true

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String, System.Management.Automation.PSModuleInfo You can pipe module names (strings) and module objects to Remove-Module.
Outputs | None Remove-Module does not generate any output.

Notes

You can also refer to Remove-Module by its alias, "rmo". For more information, see about_Aliases.

Example 1

C:\PS>remove-module -name BitsTransfer

This command removes the BitsTransfer module from the current session.

Example 2

C:\PS>get-module | remove-module

This command removes all modules from the current session.

Example 3

C:\PS>"FileTransfer", "PSDiagnostics" | remove-module -verbose

VERBOSE: Performing operation "Remove-Module" on Target "filetransfer (Path: 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\f
iletransfer\filetransfer.psd1')".
VERBOSE: Performing operation "Remove-Module" on Target "Microsoft.BackgroundIntelligentTransfer.Management (Path: 'C:\Windows\
assembly\GAC_MSIL\Microsoft.BackgroundIntelligentTransfer.Management\1.0.0.0__31bf3856ad364e35\Microsoft.BackgroundIntelligentTransfe
r.Management.dll')".
VERBOSE: Performing operation "Remove-Module" on Target "psdiagnostics (Path: 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
psdiagnostics\psdiagnostics.psd1')".
VERBOSE: Removing imported function 'Start-Trace'.
VERBOSE: Removing imported function 'Stop-Trace'.
VERBOSE: Removing imported function 'Enable-WSManTrace'.
VERBOSE: Removing imported function 'Disable-WSManTrace'.
VERBOSE: Removing imported function 'Enable-PSWSManCombinedTrace'.
VERBOSE: Removing imported function 'Disable-PSWSManCombinedTrace'.
VERBOSE: Removing imported function 'Set-LogProperties'.
VERBOSE: Removing imported function 'Get-LogProperties'.
VERBOSE: Removing imported function 'Enable-PSTrace'.
VERBOSE: Removing imported function 'Disable-PSTrace'.
VERBOSE: Performing operation "Remove-Module" on Target "PSDiagnostics (Path: 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
psdiagnostics\PSDiagnostics.psm1')".

Description
-----------
This command removes the FileTransfer and PSDiagnostics modules from the current session.

The command uses a pipeline operator (|) to send the module names to Remove-Module. It uses the Verbose common parameter to get detailed information about the members that are removed.

The Verbose messages show the items that are removed. The messages differ because the BitsTransfer module includes an assembly that implements its cmdlets and a nested module with its own assembly. The PSDiagnostics module includes a module script file (.psm1) that exports functions.

Example 4

C:\PS>$a = get-module BitsTransfer

C:\PS> remove-module -moduleInfo $a

This command uses the ModuleInfo parameter to remove the BitsTransfer module.

See Also

  • Get-Module
  • Import-Module
  • about_Modules


Remove-PSBreakpoint

Deletes breakpoints from the current console.

Syntax

Remove-PSBreakpoint [-Id] <Int32[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-PSBreakpoint [-Breakpoint] <Breakpoint[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-PSBreakpoint cmdlet deletes a breakpoint. Enter a breakpoint object or a breakpoint ID.

When you remove a breakpoint, the breakpoint object is no longer available or functional. If you have saved a breakpoint object in a variable, the reference still exists, but the breakpoint does not function.

Remove-PSBreakpoint is one of several cmdlets designed for debugging Windows PowerShell scripts. For more information about the Windows PowerShell debugger, see about_Debuggers.

Parameters

-Breakpoint <Breakpoint[]>

Specifies the breakpoints to delete. Enter a variable that contains breakpoint objects or a command that gets breakpoint objects, such as a Get-PSBreakpoint command. You can also pipe breakpoint objects to Remove-PSBreakpoint.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Id <Int32[]>

Deletes breakpoints with the specified breakpoint IDs.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.Breakpoint You can pipe breakpoint objects to Remove-PSBreakpoint.
Outputs | None The cmdlet does not generate any output.

Example 1

C:\PS>get-breakpoint | remove-breakpoint

This command deletes all of the breakpoints in the current console.

Example 2

C:\PS>$b = set-psbreakpoint -script sample.ps1 -variable Name

C:\PS> $b | remove-psbreakpoint

This command deletes a breakpoint.

The first command uses the Set-PSBreakpoint cmdlet to create a breakpoint on the Name variable in the Sample.ps1 script. Then, it saves the breakpoint object in the $b variable.

The second command uses the Remove-PSBreakpoint cmdlet to delete the new breakpoint. It uses a pipeline operator (|) to send the breakpoint object in the $b variable to the Remove-PSBreakpoint cmdlet.

As a result of this command, if you run the script, it runs to completion without stopping. Also, the Get-PSBreakpoint cmdlet does not return this breakpoint.

Example 3

C:\PS>remove-psbreakpoint -id 2

This command deletes the breakpoint with breakpoint ID 2.

Example 4

C:\PS>function del-psb { get-psbreakpoint | remove-psbreakpoint }

This simple function deletes all of the breakpoints in the current console. It uses the Get-PSBreakpoint cmdlet to get the breakpoints. Then, it uses a pipeline operator (|) to send the breakpoints to the Remove-PSBreakpoint cmdlet, which deletes them.

As a result, you can type "del-psb" instead of the longer command.

To save the function, add it to your Windows PowerShell profile.

See Also

  • about_Debuggers
  • Set-PSBreakpoint
  • Get-PSBreakpoint
  • Enable-PSBreakpoint
  • Disable-PSBreakpoint
  • Get-PSCallStack


Remove-PSDrive

Removes a Windows PowerShell drive from its location.

Syntax

Remove-PSDrive [-LiteralName] <string[]> [-Force] [-PSProvider <string[]>] [-Scope <string>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Remove-PSDrive [-Name] <string[]> [-Force] [-PSProvider <string[]>] [-Scope <string>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Remove-PSDrive cmdlet deletes Windows PowerShell drives that you created by using New-PSDrive.

Remove-PSDrive cannot delete Windows drives or mapped network drives created by using other methods and it cannot delete the current working drive.

Parameters

-Force

Allows the cmdlet to remove the current Windows PowerShell drive.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralName <string[]>

Specifies the name of the Windows PowerShell drive.

The value of LiteralName is used exactly as typed. No characters are interpreted as wildcards. If the name includes escape characters, enclose it in single quotation marks ('). Single quotation marks instruct Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the names of the Windows PowerShell drives to remove. Do not type a colon (:) after the drive name.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PSProvider <string[]>

Removes all of the Windows PowerShell drives associated with the specified Windows PowerShell provider.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Scope <string>

Accepts an index that identifies the scope from which the drive is being removed.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSDriveInfo You can pipe a drive object to Remove-PSDrive.
Outputs | None This cmdlet does not return any output.

Notes

The Remove-PSDrive cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>remove-psdrive -name smp

This command removes a Windows PowerShell drive named "smp".

See Also

  • about_Providers
  • Get-PSDrive
  • New-PSDrive


Remove-PSSession

Closes one or more Windows PowerShell sessions (PSSessions).

Syntax

Remove-PSSession [[-ComputerName] <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-PSSession [-Id] <Int32[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-PSSession [-InstanceId <Guid[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-PSSession [-Name <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-PSSession [-Session] <PSSession[]> [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-PSSession cmdlet closes Windows PowerShell sessions (PSSessions) in the current session. It stops any commands that are running in the PSSessions, ends the PSSession, and releases the resources that the PSSession was using. If the PSSession is connected to a remote computer, Remove-PSSession also closes the connection between the local and remote computers.

To remove a PSSession, enter the Name, ComputerName, ID, or InstanceID of the session.

If you have saved the PSSession in a variable, the session object remains in the variable, but the state of the PSSession is "Closed."

Parameters

-ComputerName <string[]>

Closes the PSSessions that are connected to the specified computers. Wildcards are permitted.

Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more remote computers. To specify the local computer, type the computer name, "localhost", or a dot (.).

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Id <Int32[]>

Closes the PSSessions with the specified IDs. Type one or more IDs (separated by commas) or use the range operator (..) to specify a range of IDs

An ID is an integer that uniquely identifies the PSSession in the current session. It is easier to remember and type than the InstanceId, but it is unique only within the current session. To find the ID of a PSSession, use Get-PSSession without parameters.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InstanceId <Guid[]>

Closes the PSSessions with the specified instance IDs.

The instance ID is a GUID that uniquely identifies a PSSession in the current session. The InstanceID is unique, even when you have multiple sessions running on a single computer.

The InstanceID is stored in the InstanceID property of the object that represents a PSSession. To find the InstanceID of the PSSessions in the current session, type "Get-PSSession | Format-Table Name, ComputerName, InstanceId".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Closes the PSSessions with the specified friendly names. Wildcards are permitted.

Because the friendly name of a PSSession might not be unique, when using the Name parameter, consider also using the WhatIf or Confirm parameter in the Remove-PSSession command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Session <PSSession[]>

Specifies the session objects of the PSSessions to close. Enter a variable that contains the PSSessions or a command that creates or gets the PSSessions, such as a New-PSSession or Get-PSSession command. You can also pipe one or more session objects to Remove-PSSession.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.Runspaces.PSSession You can pipe a session object to Remove-PSSession.
Outputs | None Remove-PSSession does not return any objects.

Notes

The ID parameter is mandatory. You cannot type "remove-pssession" without parameters. To delete all the PSSessions in the current session, type "Get-PSSession | remove-pssession".

A PSSession uses a persistent connection to a remote computer. Create a PSSession to run a series of commands that share data. For more information, see about_PSSessions.

PSSessions are specific to the current session. When you end a session, the PSSessions that you created in that session are forcibly closed.

Example 1

C:\PS>remove-pssession -id 1, 2

This command removes the PSSessions that have IDs 1 and 2.

Example 2

C:\PS>get-pssession | remove-pssession

C:\PS> remove-pssession -session (get-pssession)

C:\PS> $s = get-pssession
C:\PS> remove-pssession -session $s".

These commands remove all of the PSSessions in the current session. Although the three command formats look different, they have the same effect.

Example 3

C:\PS>$r = get-pssession -computername Serv*

$r | remove-pssession

These commands close the PSSessions that are connected to computers that have names that begin with "Serv".

Example 4

C:\PS>get-pssession | where {$_.port -eq 90} | remove-pssession

This command closes the PSSessions that are connected to port 90. You can use this command format to identify PSSessions by properties other than ComputerName, Name, InstanceID, and ID.

Example 5

C:\PS>get-pssession | ft computername, instanceID  -auto

ComputerName InstanceId
------------ ----------------
Server01     875d231b-2788-4f36-9f67-2e50d63bb82a
localhost    c065ffa0-02c4-406e-84a3-dacb0d677868
Server02     4699cdbc-61d5-4e0d-b916-84f82ebede1f
Server03     4e5a3245-4c63-43e4-88d0-a7798bfc2414
TX-TEST-01   fc4e9dfa-f246-452d-9fa3-1adbdd64ae85

C:\PS> remove-pssession -InstanceID fc4e9dfa-f246-452d-9fa3-1adbdd64ae85

Description
-----------
These commands show how to close a PSSession based on its instance ID (RemoteRunspaceID).

The first command uses the Get-PSsession cmdlet to get the PSSessions in the current session. It uses a pipeline operator (|) to send the PSSessions to the Format-Table cmdlet (alias: ft), which formats their ComputerName and InstanceID properties in a table. The AutoSize parameter ("auto") compresses the columns for display.

From the resulting display, the administrator can identify the PSSession to be closed, and copy and paste the InstanceID of that PSSession into the second command.

The second command uses the Remove-PSSession cmdlet to remove the PSSession with the specified instance ID.

Example 6

C:\PS>function EndPSS { get-pssession | remove-pssession }

This function deletes all of the PSSessions in the current session. After you add this function to your Windows Powershell profile, to delete all sessions, just type "endpss".

See Also

  • about_PSSessions
  • about_Remote
  • New-PSSession
  • Get-PSSession
  • Enter-PSSession
  • Exit-PSSession
  • Invoke-Command


Remove-PSSnapin

Removes Windows PowerShell snap-ins from the current session.

Syntax

Remove-PSSnapin [-Name] <string[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-PSSnapin cmdlet removes a Windows PowerShell snap-in from the current session. You can use it to remove snap-ins that you have added to Windows PowerShell, but you cannot use it to remove the snap-ins that are installed with Windows PowerShell.

After a snap-in is removed from the current session, it is still loaded, but the cmdlets and providers in the snap-in are no longer available in the session.

Parameters

-Name <string[]>

Specifies the names of Windows PowerShell snap-ins to remove from the current session. The parameter name ("Name") is optional, and wildcard characters (*) are permitted in the value.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-PassThru

Returns an object representing the snap-in. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSSnapInInfo You can pipe a snap-in object to Remove-PSSnapin.
Outputs | None or System.Management.Automation.PSSnapInInfo By default, Remove-PsSnapin does not generate any output. However, if you use the PassThru parameter, it generates a System.Management.Automation.PSSnapInInfo object representing the snap-in.

Notes

You can also refer to Remove-PSSnapin by its built-in alias, "rsnp". For more information, see about_Aliases.

Remove-PSSnapin does not check the version of Windows PowerShell before removing a snap-in from the session. If a snap-in cannot be removed, a warning appears and the command fails.

Remove-PSSnapin affects only the current session. If you have added an Add-PSSnapin command to your Windows PowerShell profile, you should delete the command to remove the snap-in from future sessions. For instructions, see about_Profiles.

Example 1

C:\PS>remove-pssnapin -name Microsoft.Exchange

This command removes the Microsoft.Exchange snap-in from the current session. When the command is complete, the cmdlets and providers that the snap-in supported are not available in the session.

Example 2

C:\PS>get-PSSnapIn smp* | remove-PSSnapIn

This command removes the Windows PowerShell snap-ins that have names beginning with "smp" from the current session.

The command uses the Get-PSSnapin cmdlet to get objects representing the snap-ins. The pipeline operator (|) sends the results to the Remove-PSSnapin cmdlet, which removes them from the session. The providers and cmdlets that this snap-in supports are no longer available in the session.

When you pipe objects to Remove-PSSnapin, the names of the objects are associated with the Name parameter, which accepts objects from the pipeline that have a Name property.

Example 3

C:\PS>remove-pssnapin -name *event*

This command removes all Windows PowerShell snap-ins that have names that include "event". This command specifies the "Name" parameter name, but the parameter name can be omitted because it is optional.

See Also

  • Add-PSSnapin
  • Get-PSSnapin
  • about_Profiles


Remove-Variable

Deletes a variable and its value.

Syntax

Remove-Variable [-Name] <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-Variable cmdlet deletes a variable and its value from the scope in which it is defined, such as the current session. You cannot use this cmdlet to delete variables that are set as constants or those that are owned by the system.

Parameters

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to remove a variable even if it is read-only. Even using the Force parameter, the cmdlet cannot remove a constant.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Deletes only the specified items. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the name of the variable to be removed. The parameter name ("Name") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Scope <string>

Specifies the scope in which this alias is valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSVariable You can pipe a variable object to Remove-Variable.
Outputs | None This cmdlet does not return any output.

Notes

Changes affect only the current scope, such as a session. To delete a variable from all sessions, add a Remove-Variable command to your Windows PowerShell profile.

You can also refer to RemoveVariable by its built-in alias, "rv". For more information, see about_Aliases.

Example 1

C:\PS>remove-variable Smp

This command deletes the $Smp variable.

See Also

  • Set-Variable
  • Get-Variable
  • Clear-Variable
  • New-Variable
  • about_Profiles


Remove-WmiObject

Deletes an instance of an existing Windows Management Instrumentation (WMI) class.

Syntax

Remove-WmiObject [-Class] <string> [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-WmiObject [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-WmiObject -InputObject <ManagementObject> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-WmiObject -Path <string> [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-WmiObject [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-WmiObject [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Remove-WmiObject cmdlet deletes an instance of an existing WMI class.

Parameters

-AsJob

Runs the command as a background job. Use this parameter to run commands that take an extensive time to complete.

Runs the command as a background job. Use this parameter to run commands that take a long time to finish.

When you use the AsJob parameter, the command returns an object that represents the background job and then displays the command prompt. You can continue to work in the session while the job finishes. If Remove-WmiObject is used against a remote computer, the job is created on the local computer, and the results from remote computers are automatically returned to the local computer. To manage the job, use the cmdlets that contain the Job noun (the Job cmdlets). To get the job results, use the Receive-Job cmdlet.

Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must start Windows PowerShell by using the "Run as administrator" option in Windows Vista and later versions of Windows,. For more information, see about_Remote_Requirements.

For more information about Windows PowerShell background jobs, see about_Jobs and about_Remote_Jobs.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationLevel>

Specifies the authentication level to be used with the WMI connection. Valid values are:

-1: Unchanged

0: Default

1: None (No authentication in performed.)

2: Connect (Authentication is performed only when the client establishes a relationship with the application.)

3: Call (Authentication is performed only at the beginning of each call when the application receives the request.)

4: Packet (Authentication is performed on all the data that is received from the client.)

5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.)

6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.)

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authority <string>

Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to "ntlmdomain:<DomainName>", where <DomainName> identifies a valid NTLM domain name. To use Kerberos, specify "kerberos:<DomainName>\<ServerName>". You cannot include the authority setting when you connect to the local computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Class <string>

Specifies the name of a WMI class that you want to delete.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name. You can set the value of this parameter by piping the value to the parameter.

This parameter does not rely on Windows PowerShell remoting, which uses WS-Management ). You can use the ComputerName parameter of Get-WmiObject even if your computer is not configured to run WS-Management remote commands.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Contoso.com". Or, enter a PSCredential object, such as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-EnableAllPrivileges

Enables all the privileges of the current user before the command makes the WMI call.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Impersonation <ImpersonationLevel>

Specifies the impersonation level to use. Valid values are:

0: Default (Reads the local registry for the default impersonation level, which is usually set to "3: Impersonate".)

1: Anonymous (Hides the credentials of the caller.)

2: Identify (Allows objects to query the credentials of the caller.)

3: Impersonate (Allows objects to use the credentials of the caller.)

4: Delegate (Allows objects to permit other objects to use the credentials of the caller.)

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ManagementObject>

Specifies a ManagementObject object to use as input. When this parameter is used, all other parameters are ignored.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Locale <string>

Specifies the preferred locale for WMI objects. The Locale parameter is specified as an array in the MS_<LCID> format in the preferred order.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Namespace <string>

When used with the Class parameter, this parameter specifies the WMI repository namespace where the referenced WMI class is located.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the WMI object path of a WMI class, or specifies the WMI object path of an instance of a WMI class to delete.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Allows the user to specify a throttling value for the number of WMI operations that can be executed simultaneously. This parameter is used together with the AsJob parameter. The throttle limit applies only to the current command, not to the session or to the computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.ManagementObject You can pipe a management object to Remove-WmiObject.
Outputs | None or System.Management.Automation.RemotingJob When you use the AsJob parameter, this cmdlet returns a job object. Otherwise, it does not generate any output.

Example 1

C:\PS>notepad
C:\PS> $np = get-wmiobject -query "select * from win32_process where name='notepad.exe'"
C:\PS> $np | remove-wmiobject

This command closes all the instances of Notepad.exe.

The first command starts an instance of Notepad.

The second command uses the Get-WmiObject cmdlet to retrieve the instances of the Win32_Process that correspond to Notepad.exe and stores them in the $np variable.

The third command passes the object in the $np variable to the Remove-WmiObject cmdlet, which deletes all the instances of Notepad.exe.

Example 2

C:\PS>$a = Get-WMIObject -query "Select * From Win32_Directory Where Name ='C:\\Test'"
C:\PS> $a | Remove-WMIObject

This command deletes the C:\Test directory.

The first command uses the Get-WMIObject cmdlet to query for the C:\Test directory and then stores the object in the $a variable.

The second command pipes the $a variable to the Remove-WMIObject, which deletes the directory.

See Also

  • Get-WmiObject
  • Invoke-WmiMethod
  • Set-WmiInstance
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • Remove-WSManInstance


Remove-WSManInstance

Deletes a management resource instance.

Syntax

Remove-WSManInstance [-ApplicationName <string>] [-ComputerName <string>] [-Port <int>] [-UseSSL] [[-SelectorSet] <hashtable>] [-AuthenticationMechanism <AuthenticationMechanism>] [-Credential <PSCredential>] [-OptionSet <hashtable>] [-ResourceURI <Uri>] [-SessionOption <hashtable>] [<CommonParameters>]

Remove-WSManInstance [-ConnectionURI <Uri>] [[-SelectorSet] <hashtable>] [-AuthenticationMechanism <AuthenticationMechanism>] [-Credential <PSCredential>] [-OptionSet <hashtable>] [-ResourceURI <Uri>] [-SessionOption <hashtable>] [<CommonParameters>]

Description

The Remove-WSManInstance deletes an instance of a management resource that is specified in the ResourceURI and SelectorSet parameters.

This cmdlet uses the WinRM connection/transport layer to delete the management resource instance.

Parameters

-ApplicationName <string>

Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for the remote endpoint is in the following format:

<transport>://<server>:<port>/<ApplicationName>

For example:

http://server01:8080/WSMAN

Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency.

Required? | false
Position? | named
Default Value | wsman
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AuthenticationMechanism <AuthenticationMechanism>

Specifies the authentication mechanism to be used at the server. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.

- Default : Use the authentication method implemented by the WS-Management protocol. This is the default.

- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

- Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates.

- Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.

- CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

Caution: CredSSP delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

Required? | false
Position? | named
Default Value | localhost
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ConnectionURI <Uri>

Specifies the connection endpoint. The format of this string is:

<Transport>://<Server>:<Port>/<ApplicationName>

The following string is a properly formatted value for this parameter:

http://Server01:8080/WSMAN

The URI must be fully qualified.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Domain.com". Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-OptionSet <hashtable>

Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified.

The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters:

-OptionSet @{a=1;b=2;c=3}

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Port <int>

Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server's certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted computers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ResourceURI <Uri>

Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer.

A URI consists of a prefix and a path to a resource. For example:

http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk

http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SelectorSet <hashtable>

Specifies a set of value pairs that are used to select particular management resource instances. The SelectorSet parameter is used when more than one instance of the resource exists. The value of the SelectorSet parameter must be a hash table.

The following example shows how to enter a value for this parameter:

-SelectorSet @{Name="WinRM";ID="yyy"}

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-SessionOption <hashtable>

Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, see New-WSManSessionOption.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Notes

The Remove-WmiObject cmdlet, a Windows Management Instrumentation (WMI) cmdlet, is similar. Remove-WmiObject uses the DCOM connection/transport layer to create or update WMI instances.

Example 1

C:\PS>Remove-WSManInstance winrm/config/Listener -SelectorSet Address=test.fabrikam.com;Transport=http

Deletes the WS-Management HTTP listener on a computer.

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Set-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan
  • Remove-WmiObject


Rename-Item

Renames an item in a Windows PowerShell provider namespace.

Syntax

Rename-Item [-Path] <string> [-NewName] <string> [-Credential <PSCredential>] [-Force] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Rename-Item cmdlet changes the name of a specified item. This cmdlet does not affect the content of the item being renamed.

You cannot use Rename-Item to move an item, such as by specifying a path along with the new name. To move and rename an item, use the Move-Item cmdlet.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to rename items that cannot otherwise be changed, such as hidden or read-only files or read-only aliases or variables. The cmdlet cannot change constant aliases or variables. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NewName <string>

Specifies the new name of the item. Enter only a name, not a path and name. If you enter a path that is different from the path that is specified in the Path parameter, Rename-Item generates an error. To rename and move an item, use the Move-Item cmdlet.

You cannot use wildcard characters in the value of NewName. To specify a name for multiple files, use the Replace operator in a regular expression. For more information about the Replace operator, type "Get-Help about_Comparison_Operators". For a demonstration, see the examples.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Passes an object representing the item to the pipeline. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the path to the item to rename.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Rename-Item.
Outputs | None or an object representing the renamed item. When you use the Passthru parameter, Rename-Item generates an object representing the renamed item. Otherwise, this cmdlet does not generate any output.

Notes

The Rename-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>rename-item -path c:\logfiles\daily_file.txt -newname monday_file.txt

This command renames the file daily_file.txt to monday_file.txt.

Example 2

C:\PS>rename-item -path project.txt -newname d:\archive\old-project.txt

Rename-Item : Cannot rename because the target specified represents a path or device name.
At line:1 char:12
+ rename-item <<<<  -path project.txt -newname d:\archive\old-project.txt
    + CategoryInfo          : InvalidArgument: (:) [Rename-Item], PSArgumentException
    + FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RenameItemCommand

C:\PS> move-item -path project.txt -destination d:\archive\old-project.txt
# Command succeeds

Description
-----------
This example shows that you cannot use the Rename-Item cmdlet to both rename and move an item. Specifically, you cannot supply a path for the value of the NewName parameter, unless the path is identical to the path specified in the Path parameter. Otherwise, only a new name is permitted.

The first command uses the Rename-Item cmdlet to rename the project.txt file in the current directory to old-project.txt in the D:\Archive directory. The result is the error shown in the output.

The second command shows the correct way to move and rename a file by using the Move-Item cmdlet. The Move-Item cmdlet lets you specify both a new path and a new name in the value of its Destination parameter.

Example 3

C:\PS>rename-item HKLM:\Software\MyCompany\Advertising -NewName Marketing

This command uses the Rename-Item cmdlet to rename a registry key from Advertising to Marketing. When the command is complete, the key is renamed, but the registry entries in the key are unchanged.

Example 4

C:\PS>get-childItem *.txt | rename-item -newname { $_.name -replace '\.txt','.log' }

This example shows how to use the Replace operator to rename multiple files, even though the NewName parameter does not accept wildcard characters.

This command renames all of the .txt files in the current directory to .log.

The command uses a Get-ChildItem cmdlet to get all of the files in the current directory that have a .txt file name extension. Then, it uses the pipeline operator (|) to send the resulting files to the Rename-Item cmdlet.

In the Rename-Item command, the value of the NewName parameter is a script block that is executed before the value is submitted to the NewName parameter.

In the script block, the $_ automatic variable represents each file object as it comes to the command through the pipeline. The command uses the dot format (.) to get the Name property of each file object. The Replace operator replaces the ".txt" file name extension of each file with ".log".

Because the Replace operator works with regular expressions, the dot preceding "txt" is interpreted to match any character. To ensure that it matches only a dot (.), it is escaped with a backslash character (\). The backslash character is not required in ".log" because it is a string, not a regular expression.

See Also

  • about_Providers
  • Clear-Item
  • Invoke-Item
  • Move-Item
  • Rename-ItemProperty
  • Set-Item
  • New-Item
  • Remove-Item
  • Get-Item
  • Copy-Item


Rename-ItemProperty

Renames a property of an item.

Syntax

Rename-ItemProperty [-LiteralPath] <string> [-Name] <string> [-NewName] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Rename-ItemProperty [-Path] <string> [-Name] <string> [-NewName] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Rename-ItemProperty cmdlet changes the name of a specified item property. The value of the property is not changed. For example, you can use Rename-ItemProperty to change the name of a registry entry.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to rename a property of an object that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see about_Providers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Specifies only those items upon which the cmdlet will act, excluding all others.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string>

Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string>

Specifies the current name of the property to be renamed.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-NewName <string>

Specifies the new name for the property.

Required? | true
Position? | 3
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the item property. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies the path to the item to be renamed.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path (but not a literal path) to Rename-ItemProperty.
Outputs | None or System.Management.Automation.PSCustomObject When you use the PassThru parameter, Rename-ItemProperty generates a PSCustomObject representing the renamed item property. Otherwise, this cmdlet does not generate any output.

Notes

The Remove-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>rename-itemproperty -path HKLM:\Software\SmpApplication -name config -newname oldconfig

This command renames the config registry entry contained in the HKEY_LOCAL_MACHINE\Software\SmpApplication key to oldconfig.

See Also

  • about_Providers
  • Rename-Item
  • Clear-ItemProperty
  • Copy-ItemProperty
  • Get-ItemProperty
  • Move-ItemProperty
  • New-ItemProperty
  • Remove-ItemProperty
  • Set-ItemProperty


Reset-ComputerMachinePassword

Resets the machine account password for the computer.

Syntax

Reset-ComputerMachinePassword [-Server <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Reset-ComputerMachinePassword cmdlet changes the machine account password that the computers use to authenticate to the domain controllers in the domain. You can use it to reset the password of the local computer.

Parameters

-Server <string>

Specifies the name of a domain controller to use when setting the machine account password.

This parameter is optional. If you omit this parameter, a domain controller is chosen to service the command.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>Reset-ComputerMachinePassword

This command resets the machine password for the local computer. The command runs with the credentials of the current user.

Example 2

C:\PS>Reset-ComputerMachinePassword -server DC01

This command resets the machine password of the local computer using the DC01 domain controller.

Example 3

C:\PS>invoke-command -computername Server01 -scriptblock {reset-computermachinepassword}

This command uses the Invoke-Command cmdlet to run a Reset-ComputerMachinePassword command on the Server01 remote computer.

For more information about remote commands in Windows PowerShell, see about_Remote and Invoke-Command.


Resolve-Path

Resolves the wildcard characters in a path, and displays the path contents.

Syntax

Resolve-Path [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Relative] [-UseTransaction] [<CommonParameters>]

Resolve-Path [-Path] <string[]> [-Credential <PSCredential>] [-Relative] [-UseTransaction] [<CommonParameters>]

Description

The Resolve-Path cmdlet interprets the wildcard characters in a path and displays the items and containers at the location specified by the path, such as the files and folders or registry keys and subkeys.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the path to be resolved. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the Windows PowerShell path to resolve. This parameter is required. You can also pipe a path string to Resolve-Path.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Relative

Returns a relative path.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Resolve-Path.
Outputs | System.String Resolve-Path returns a string that contains the resolved path.

Notes

The cmdlets that contain the Path noun (the Path cmdlets) manipulate path names and return the names in a concise format that all Windows PowerShell providers can interpret. They are designed for use in programs and scripts where you want to display all or part of a path name in a particular format. Use them like you would use Dirname, Normpath, Realpath, Join, or other path manipulators.

You can use the Path cmdlets with several providers, including the FileSystem, Registry, and Certificate providers.

The Resolve-Path cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>resolve-path ~

C:\Users\User01

Description
-----------
This command resolves the path represented by the tilde character (~), which signifies the home path.

Example 2

C:\PS>resolve-path windows

C:\Windows

Description
-----------
When run from the root of the C: drive, this command returns the path to the Windows directory in the C: drive.

Example 3

C:\PS>"C:\windows\*" | resolve-path

This command returns all of the directories in the C:\Windows directory. The command uses a pipeline operator (|) to send a path string to Resolve-Path.

Example 4

C:\PS>resolve-path \\Server01\public

This command resolves a Universal Naming Convention (UNC) path and returns the shares in the path.

Example 5

C:\PS>resolve-path c:\prog* -relative

..\Program Files
..\Program Files (x86)
..\programs.txt

Description
-----------
This command returns relative paths for the directories at the root of the C: drive.

Example 6

C:\PS>resolve-path -literalPath test[xml]

This command resolves the path to the Test[xml] subdirectory of the current directory. It uses the LiteralPath parameter to indicate that the brackets are not regular expression characters.

See Also

  • about_Providers
  • Test-Path
  • Split-Path
  • Convert-Path
  • Join-Path


Restart-Computer

Restarts ("reboots") the operating system on local and remote computers.

Syntax

Restart-Computer [[-ComputerName] <string[]>] [[-Credential] <PSCredential>] [-AsJob] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Force] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Restart-Computer cmdlet restarts the operating system on the local and remote computers.

You can use the parameters of Restart-Computer to run the restart operations as a background job, to specify the authentication levels and alternate credentials, to limit the operations that run concurrently, and to force an immediate restart.

This cmdlet does not require Windows PowerShell remoting unless you use the AsJob parameter.

Parameters

-AsJob

Runs the command as a background job.

Note: To use this parameter, the local and remote computers must be configured for remoting and, on Windows Vista and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option. For more information, see about_Remote_Requirements.

When you use the AsJob parameter, the command immediately returns an object that represents the background job. You can continue to work in the session while the job completes. The job is created on the local computer and the results from remote computers are automatically returned to the local computer. To manage the job, use the Job cmdlets. To get the job results, use the Receive-Job cmdlet.

For more information about Windows PowerShell background jobs, see about_Jobs and about_Remote_Jobs.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationLevel>

Specifies the authentication level that is used for the WMI connection. (Restart-Computer uses WMI.) The default value is Packet.

Valid values are:

Unchanged: The authentication level is the same as the previous command.

Default: Windows Authentication

None: No COM authentication

Connect: Connect-level COM authentication

Call: Call-level COM authentication

Packet: Packet-level COM authentication.

PacketIntegrity: Packet Integrity-level COM authentication

PacketPrivacy: Packet Privacy-level COM authentication.

Required? | false
Position? | named
Default Value | 4
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Specifies one or more remote computers. The default is the local computer.

Type the NETBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter even if your computer is not configured to run remote commands.

Required? | false
Position? | 1
Default Value | .
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one from the Get-Credential cmdlet.

Required? | false
Position? | 2
Default Value | Current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Forces an immediate restart of the computers.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Impersonation <ImpersonationLevel>

Specifies the impersonation level to use when calling WMI. (Restart-Computer uses WMI.) The default value is "Impersonate".

Valid values are:

Default: Default impersonation.

Anonymous: Hides the identity of the caller.

Identify: Allows objects to query the credentials of the caller.

Impersonate: Allows objects to use the credentials of the caller.

Required? | false
Position? | named
Default Value | Impersonate
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.

The throttle limit applies only to the current command, not to the session or to the computer.

Required? | false
Position? | named
Default Value | 32
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None or System.Management.Automation.RemotingJob When you use the AsJob parameter, the cmdlet returns a job object. Otherwise, it does not generate any output.

Notes

This cmdlet uses the Win32Shutdown method of the WMI WIN32_OperatingSystem class.

Example 1

C:\PS>restart-computer

This command restarts the local computer.

Example 2

C:\PS>restart-computer -computername Server01, Server02, localhost

This command restarts two remote computers, Server01 and Server02, and the local computer, identified as "localhost".

Example 3

C:\PS>$j = restart-computer -computername Server01, Server02 -asjob

C:\PS> $results = $j | receive-job

C:\PS> $results

These commands run a Restart-Computer command as a background job on two remote computers, and then get the results.

The first command uses the AsJob parameter to run the command as a background job. The command saves the resulting job object in the $j variable.

The second command uses a pipeline operator to send the job object in $j to the Receive-Job cmdlet, which gets the job results. The command saves the results in the $results variable.

The third command displays the result saved in the $results variable.

Because the AsJob parameter creates the job on the local computer and automatically returns the results to the local computer, you can run the Receive-Job command as a local command.

Example 4

C:\PS>restart-computer -comp Server01 -impersonation anonymous -authentication PacketIntegrity

This command restarts the Server01 remote computer. The command uses customized impersonation and authentication settings.

Example 5

C:\PS>$s = get-content domain01.txt

C:\PS> $c = get-credential domain01\admin01

C:\PS> restart-computer -computername $s -force -throttlelimit 10 -credential $c

These commands force an immediate restart of all of the computers in Domain01.

The first command gets a list of computers in the domain and saves it in the $s variable.

The second command gets the credentials of a domain administrator and saves them in the $c variable.

The third command restarts the computers. It uses the ComputerName parameter to submit the list of computers in the $s variable, the Force parameter to force an immediate restart, and the Credential parameter to submit the credentials saved in the $c variable. It also uses the ThrottleLimit parameter to limit the command to 10 concurrent connections.

See Also

  • Add-Computer
  • Checkpoint-Computer
  • Remove-Computer
  • Restore-Computer
  • Stop-Computer
  • Test-Connection


Restart-Service

Stops and then starts one or more services.

Syntax

Restart-Service [-Name] <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Restart-Service -DisplayName <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Restart-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Restart-Service cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. If a service was already stopped, it is started without notifying you of an error. You can specify the services by their service names or display names, or you can use the InputObject parameter to pass an object that represents each service that you want to restart.

Parameters

-DisplayName <string[]>

Specifies the display names of services to be restarted. Wildcards are permitted.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Overrides restrictions that prevent the command from succeeding, just so the changes do not compromise security. For example, Force will stop and restart a service that has dependent services.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Restarts only the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ServiceController[]>

Specifies ServiceController objects that represent the services to be restarted. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the service names of the services to be restarted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object that represents the service. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.ServiceProcess.ServiceController, System.String You can pipe a service object or a string that contains a service name to Restart-Service.
Outputs | None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Restart-Service generates a System.ServiceProcess.ServiceController object that represents the restarted service. Otherwise, this cmdlet does not generate any output.

Notes

Restart-Service can control services only when the current user has permission to do so. If a command does not work correctly, you might not have the required permissions.

To find the service names and display names of the services on your system, type "Get-Service". The service names appears in the Name column, and the display names appear in the DisplayName column.

Example 1

C:\PS>restart-service wmi

This command restarts the Windows Management Instrumentation (WMI) service on the local computer.

Example 2

C:\PS>restart-service -displayname net* -exclude "net logon"

This command restarts the services that have a display name that begins with "Net", except for the "Net Logon" service.

Example 3

C:\PS>get-service net* | where-object {$_.Status -eq "Stopped"} | restart-service

This command starts all of the stopped network services on the computer.

It uses the Get-Service cmdlet to get objects representing the services whose service name begins with "net". (The optional Name parameter name is omitted.) The pipeline operator (|) sends the services object to the Where-Object cmdlet, which selects only the services with a status of "stopped." Another pipeline operator sends the selected services to Restart-Service. In practice, you would use the WhatIf parameter to see the effect of the command before using it.

See Also

  • Start-Service
  • Stop-Service
  • Suspend-Service
  • Resume-Service
  • New-Service
  • Get-Service
  • Set-Service


Restore-Computer

Starts a system restore on the local computer.

Syntax

Restore-Computer [-RestorePoint] <int> [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Restore-Computer cmdlet restores the local computer to the specified system restore point.

A Restore-Computer command restarts the computer. The restore is completed during the restart operation.

Parameters

-RestorePoint <int>

Specifies the sequence number of the restore point. To find the sequence number, use Get-ComputerRestorePoint. This parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not generate any output.

Notes

To run a Restore-Computer command on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administrator" option.

This cmdlet uses the Windows Management Instrumentation (WMI) SystemRestore class.

Example 1

C:\PS>restore-computer -RestorePoint 253

This command restores the local computer to the restore point with sequence number 253.

Because the RestorePoint parameter is positional, you can omit the parameter name.

Example 2

C:\PS>restore-computer 255 -confirm

Confirm
Are you sure you want to perform this action?
Performing operation "Restore-Computer" .
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

Description
-----------
This command restores the local computer to the restore point with sequence number 255. It uses the Confirm parameter to prompt the user before actually performing the operation.

Example 3

C:\PS>Get-ComputerRestorePoint

C:\PS> Restore-Computer -RestorePoint 255

C:\PS> Get-ComputerRestorePoint -LastStatus

These commands run a system restore and then check its status.

The first command uses the Get-ComputerRestorePoint cmdlet to get the restore points on the local computer.

The second command uses Restore-Computer to restore the computer to the restore point with sequence number 255.

The third command uses the LastStatus parameter of Get-ComputerRestorePoint cmdlet to check the status of the restore operation. Because the Restore-Computer command forces a restart, this command would be entered when the computer restarted.

See Also

  • Get-ComputerRestorePoint
  • Enable-ComputerRestore
  • Disable-ComputerRestore
  • Restart-Computer


Resume-Service

Resumes one or more suspended (paused) services.

Syntax

Resume-Service [-Name] <string[]> [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Resume-Service -DisplayName <string[]> [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Resume-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Resume-Service cmdlet sends a resume message to the Windows Service Controller for each of the specified services. If they have been suspended, they will resume service. If they are currently running, the message is ignored. You can specify the services by their service names or display names, or you can use the InputObject parameter to pass a service object that represents the services that you want to resume.

Parameters

-DisplayName <string[]>

Specifies the display names of the services to be resumed. Wildcards are permitted.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Resumes only the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ServiceController[]>

Specifies ServiceController objects representing the services to be resumed. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the service names of the services to be resumed.

The parameter name is optional. You can use "-Name" or its alias, "-ServiceName", or you can omit the parameter name.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the service. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.ServiceProcess.ServiceController or System.String You can pipe a service object or a string that contains a service name to Resume-Service.
Outputs | None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Resume-Service generates a System.ServiceProcess.ServiceController object representing the resumed service. Otherwise, this cmdlet does not generate any output.

Notes

The status of services that have been suspended is "Paused". When services are resumed, their status is "Running".

Resume-Service can control services only when the current user has permission to do so. If a command does not work correctly, you might not have the required permissions.

To find the service names and display names of the services on your system, type "Get-Service". The service names appear in the Name column, and the display names appear in the DisplayName column.

Example 1

C:\PS>resume-service sens

This command resumes the System Event Notification service (the service name is represented in the command by "sens") on the local computer. The command uses the Name parameter to specify the service name of the service, but the command omits the parameter name because the parameter name is optional.

Example 2

C:\PS>get-service | where-object {$_.Status -eq "Paused"} | resume-service

This command resumes all of the suspended (paused) services on the computer. The first command gets all of the services on the computer. The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects the services with a Status property of "Paused". The next pipeline operator sends the results to Resume-Service, which resumes the paused services.

In practice, you would use the WhatIf parameter to determine the effect of the command before running it without WhatIf.

See Also

  • Get-Service
  • Start-Service
  • Stop-Service
  • Restart-Service
  • Suspend-Service
  • Set-Service
  • New-Service


Select-Object

Selects specified properties of an object or set of objects. It can also select unique objects from an array of objects, or it can select a specified number of objects from the beginning or end of an array of objects.

Syntax

Select-Object [[-Property] <Object[]>] [-ExcludeProperty <string[]>] [-ExpandProperty <string>] [-First <int>] [-InputObject <psobject>] [-Last <int>] [-Skip <int>] [-Unique] [<CommonParameters>]

Select-Object [-Index <Int32[]>] [-InputObject <psobject>] [-Unique] [<CommonParameters>]

Description

The Select-Object cmdlet gets only the specified properties of an object or set of objects. It can also select unique objects from an array of objects, or it can select a specified number of objects from the beginning or end of an array of objects.

If you use Select-Object to select specified properties, it copies the values of those properties from the input objects and creates new objects that have the specified properties and copied values.

Use the Property parameter to specify the properties you want to select. Or, use the First, Last, Unique, Skip, and Index parameters to select particular objects from an array of input objects. For more specific object filtering, use the Where-Object cmdlet.

Parameters

-ExcludeProperty <string[]>

Removes the specifies properties from the selection. Wildcards are permitted. This parameter is effective only when the command also includes the Property parameter.

The value of the property parameter can be a calculated property, which is a hash table that specifies a name and calculates a value for the property display. Valid keys are:

-- Name or Label <string>

-- Expression <string> or <scriptblock>

For more information, see the examples.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-ExpandProperty <string>

Specifies a property to select, and indicates that an attempt should be made to expand that property. Wildcards are permitted in the property name.

For example, if the specified property is an array, each value of the array is included in the output. If the property contains an object, the properties of that object are displayed in the output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-First <int>

Specifies the number of objects to select from the beginning of an array of input objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Index <Int32[]>

Selects objects from an array based on their index values. Enter the indexes in a comma-separated list.

Indexes in an array begin with 0, where 0 represents the first value and (n-1) represents the last value.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies objects to send to the cmdlet through the pipeline. This parameter enables you to pipe objects to Select-Object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Last <int>

Specifies the number of objects to select from the end of an array of input objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Property <Object[]>

Specifies the properties to select. Wildcards are permitted.

The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Name (or Label) <string>

-- Expression <string> or <script block>

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Skip <int>

Skips (does not select) the specified number of items. By default, the Skip parameter counts from the beginning of the array or list of objects, but if the command uses the Last parameter, it counts from the end of the list or array.

Unlike the Index parameter, which starts counting from 0, the Skip parameter begins at 1.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Unique

Specifies that if a subset of the input objects has identical properties and values, only a single member of the subset will be selected.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object to Select-Object.
Outputs | System.Management.Automation.PSObject

Notes

You can also refer to Select-Object by its built-in alias, "select". For more information, see about_Aliases.

Example 1

C:\PS>get-process | select-object ProcessName,Id,WS

This command displays a list of processes. Only the name, ID, and working set (WS) properties of the processes are displayed.

Example 2

C:\PS>get-process | select-object processname -expandproperty modules |
format-list

ProcessName       : 00THotkey
Size              : 256
Company           : TOSHIBA Corporation
FileVersion       : 1, 0, 0, 27
ProductVersion    : 6, 2, 0, 0
Description       : THotkey
Product           : TOSHIBA THotkey
ModuleName        : 00THotkey.exe
FileName          : C:\WINDOWS\system32\00THotkey.exe
BaseAddress       : 4194304

Description
-----------
This command displays information about the modules used by the processes running on a computer. It uses the ExpandProperty parameter to display the details contained within the modules property.

Example 3

C:\PS>get-process | sort-object -property WS | select-object -Last 5

Handles  NPM(K)    PM(K)      WS(K) VS(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
   2866     320    33432      45764   203   222.41   1292 svchost
    577      17    23676      50516   265    50.58   4388 WINWORD
    826      11    75448      76712   188    19.77   3780 Ps
   1367      14    73152      88736   216    61.69    676 Ps
   1612      44    66080      92780   380   900.59   6132 INFOPATH

Description
-----------
This command displays the five processes that are using the most memory. The Sort-Object cmdlet is used to sort the processes according to memory (working set) usage, and the Select-Object cmdlet is used to select only the last five members of the resulting array of objects.

Example 4

C:\PS>get-process | select-object -property ProcessName,@{Name="Start Day"; Expression = {$_.StartTime.DayOfWeek}}

ProcessName  StartDay
----         --------
alg          Wednesday
ati2evxx     Wednesday
ati2evxx     Thursday
...

Description
-----------
This command displays the name and start day of the processes running on a computer.

The values of the Property parameter are ProcessName and a calculated property named "Start Day." The "Start Day" property is added by using a hash table with Name and Expression keys.

Example 5

C:\PS>"a","b","c","a","a","a" | select-object -unique

a
b
c

Description
-----------
This command displays unique characters from an array of characters.

Example 6

C:\PS>$a = get-eventlog -log "Windows PowerShell"

C:\PS> $a | select-object -index 0, ($a.count - 1)

These commands get the first (newest) and last (oldest) events in the Windows Powershell event log.

The first command uses the Get-EventLog cmdlet to get all events in the Windows Powershell log. It saves the events in the $a variable.

The second command uses a pipeline operator (|) to send the events in $a to the Select-Object cmdlet. The Select-Object command uses the Index parameter to select items by their index number. The index for the first event is 0. The index for the last event is the number of items in $a minus 1.

Example 7

C:\PS>new-pssession -computername (get-content servers.txt | select-object -skip 1)

This command creates a new PSSession on each of the computers listed in the Servers.txt files, except for the first one.

This command uses the Select-Object cmdlet to select all but the first computer in a list of computer names. The resulting list of computers is set as the value of the ComputerName parameter of the New-PSSession cmdlet.

See Also

  • Where-Object
  • Group-Object
  • Sort-Object


Select-String

Finds text in strings and files.

Syntax

Select-String [-Path] <string[]> [-Pattern] <string[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>] [-Encoding <string>] [-Exclude <string[]>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonParameters>]

Select-String -InputObject <psobject> [-Pattern] <string[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>] [-Encoding <string>] [-Exclude <string[]>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonParameters>]

Description

The Select-String cmdlet searches for text and text patterns in input strings and files. You can use it like Grep in UNIX and Findstr in Windows.

Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

However, you can direct it to detect multiple matches per line, display text before and after the match, or display only a Boolean value (true or false) that indicates whether a match is found.

Select-String uses regular expression matching, but it can also perform a simple match that searches the input for the text that you specify.

Select-String can display all of the text matches or stop after the first match in each input file. It can also display all text that does not match the specified pattern.

You can also specify that Select-String should expect a particular character encoding, such as when you are searching files of Unicode text.

Parameters

-AllMatches

Searches for more than one match in each line of text. Without this parameter, Select-String finds only the first match in each line of text.

When Select-String finds more than one match in a line of text, it still emits only one MatchInfo object for the line, but the Matches property of the object contains all of the matches.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CaseSensitive

Makes matches case-sensitive. By default, matches are not case-sensitive.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Context <Int32[]>

Captures the specified number of lines before and after the line with the match. This allows you to view the match in context.

If you enter one number as the value of this parameter, that number determines the number of lines captured before and after the match. If you enter two numbers as the value, the first number determines the number of lines before the match and the second number determines the number of lines after the match.

In the default display, lines with a match are indicated by a right angle bracket (ASCII 62) in the first column of the display. Unmarked lines are the context.

This parameter does not change the number of objects generated by Select-String. Select-String generates one MatchInfo (Microsoft.PowerShell.Commands.MatchInfo) object for each match. The context is stored as an array of strings in the Context property of the object.

When you pipe the output of a Select-String command to another Select-String command, the receiving command searches only the text in the matched line (the value of the Line property of the MatchInfo object), not the text in the context lines. As a result, the Context parameter is not valid on the receiving Select-String command.

When the context includes a match, the MatchInfo object for each match includes all of the context lines, but the overlapping lines appear only once in the display.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Encoding <string>

Specifies the character encoding that Select-String should assume when searching the file. The default is UTF8.

Valid values are "UTF7", "UTF8", "UTF32", "ASCII", "Unicode", "BigEndianUnicode", "Default", and "OEM". "Default" is the encoding of the system's current ANSI code page. "OEM" is the current original equipment manufacturer code page identifier for the operating system.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Exclude the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Include only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the text to be searched. Enter a variable that contains the text, or type a command or expression that gets the text.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-List

Returns only the first match in each input file. By default, Select-String returns a MatchInfo object for each match it finds.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NotMatch

Finds text that does not match the specified pattern.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the files to be searched. Wildcards are permitted. The default location is the local directory.

Specify files in the directory, such as "log1.txt", "*.doc", or "*.*". If you specify only a directory, the command fails.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Pattern <string[]>

Specifies the text to find. Type a string or regular expression. If you type a string, use the SimpleMatch parameter.

To learn about regular expressions, see about_Regular_Expressions.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Quiet

Returns a Boolean value (true or false), instead of a MatchInfo object. The value is "true" if the pattern is found; otherwise, the value is "false".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SimpleMatch

Uses a simple match rather than a regular expression match. In a simple match, Select-String searches the input for the text in the Pattern parameter. It does not interpret the value of the Pattern parameter as a regular expression statement.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe any object that has a ToString method to Select-String.
Outputs | Microsoft.PowerShell.Commands.MatchInfo or System.Boolean By default, the output is a set of MatchInfo objects, one for each match found. If you use the Quiet parameter, the output is a Boolean value indicating whether the pattern was found.

Notes

Select-String is like the Grep command in UNIX and the FindStr command in Windows.

To use Select-String, type the text that you want to find as the value of the Pattern parameter.

To specify the text to be searched, do the following:

-- Type the text in a quoted string, and then pipe it to Select-String.

-- Store a text string in a variable, and then specify the variable as the value of the InputObject parameter.

-- If the text is stored in files, use the Path parameter to specify the path to the files.

By default, Select-String interprets the value of the Pattern parameter as a regular expression. (For more information, see about_Regular_Expressions.) However, you can use the SimpleMatch parameter to override the regular expression matching. The SimpleMatch parameter finds instances of the value of the Pattern parameter in the input.

The default output of Select-String is a MatchInfo object, which includes detailed information about the matches. The information in the object is useful when you are searching for text in files, because MatchInfo objects have properties such as Filename and Line. When the input is not from the file, the value of these parameters is "InputStream".

If you do not need the information in the MatchInfo object, use the Quiet parameter, which returns a Boolean value (true or false) to indicate whether it found a match, instead of a MatchInfo object.

When matching phrases, Select-String uses the current that is set for the system. To find the current culture, use the Get-Culture cmdlet.

To find the properties of a MatchInfo object, type the following:

select-string -path test.txt -pattern "test" | Get-Member | Format-List -property *

Example 1

C:\PS>"Hello","HELLO" | select-string -pattern "HELLO" -casesensitive

This command performs a case-sensitive match of the text that was piped to the Select-String command.

As a result, Select-String finds only "HELLO", because "Hello" does not match.

Because each of the quoted strings is treated as a line, without the CaseSensitive parameter, Select-String would recognize both of the strings as matches.

Example 2

C:\PS>select-string -path *.xml -pattern "the the"

This command searches through all files with the .xml file name extension in the current directory and displays the lines in those files that include the string "the the".

Example 3

C:\PS>select-string -path $pshome\en-US\*.txt -pattern "@"

This command searches the Windows PowerShell conceptual Help files (about_*.txt) for information about the use of the at sign (@).

To indicate the path, this command uses the value of the $pshome automatic variable, which stores the path to the Windows PowerShell installation directory. In this example, the command searches the en-US subdirectory, which contains the English (US) language Help files for Windows PowerShell.

Example 4

C:\PS>function search-help
{
    $pshelp = "$pshome\es\about_*.txt", "$pshome\en-US\*dll-help.xml"
    select-string -path $pshelp -pattern $args[0]
}

This simple function uses the Select-String cmdlet to search the Windows PowerShell Help files for a particular string. In this example, the function searches the "en-US" subdirectory for English-United States language files.

To use the function to find a string, such as "psdrive", type "search-help psdrive".

To use this function in any Windows PowerShell console, change the path to point to the Windows PowerShell Help files on your system, and then paste the function in your Windows PowerShell profile.

Example 5

C:\PS>$events = get-eventlog -logname application -newest 100

C:\PS> $events | select-string -inputobject {$_.message} -pattern "failed"

This example searches for the string "failed" in the 100 newest events in the Application log in Event Viewer.

The first command uses the Get-EventLog cmdlet to get the 100 most recent events from the Application event log. Then it stores the events in the $events variable.

The second command uses a pipeline operator (|) to send the objects in the $events variable to Select-String. It uses the InputObject parameter to represent the input from the $events variable. The value of the InputObject parameter is the Message property of each object as it travels through the pipeline. The current object is represented by the $_ symbol.

As each event arrives in the pipeline, Select-String searches the value of its Message property for the "failed" string, and then displays any lines that include a match.

Example 6

C:\PS>get-childitem c:\windows\system32\* -include *.txt -recurse |
select-string -pattern "Microsoft" -casesensitive

This command examines all files in the subdirectories of C:\Windows\System32 with the .txt file name extension and searches for the string "Microsoft". The CaseSensitive parameter indicates that the "M" in "Microsoft" must be capitalized and that the rest of the characters must be lowercase for Select-String to find a match.

Example 7

C:\PS>select-string -path process.txt -pattern idle, svchost -notmatch

This command finds lines of text in the Process.txt file that do not include the words "idle" or "svchost".

Example 8

C:\PS>$f = select-string -path audit.log -pattern "logon failed" -context 2, 3

C:\PS> $f.count

C:\PS> ($f)[0].context | format-list

The first command searches the Audit.Log file for the phrase "logon failed." It uses the Context parameter to capture 2 lines before the match and 3 lines after the match.

The second command uses the Count property of object arrays to display the number of matches found, in this case, 2.

The third command displays the lines stored in the Context property of the first MatchInfo object. It uses array notation to indicate the first match (match 0 in a zero-based array), and it uses the Format-List cmdlet to display the value of the Context property as a list.

The output consists of two MatchInfo objects, one for each match detected. The context lines are stored in the Context property of the MatchInfo object.

Example 9

C:\PS>$a = get-childitem $pshome\en-us\about*.help.txt | select-string -pattern transcript

C:\PS> $b = get-childitem $pshome\en-us\about*.help.txt | select-string -pattern transcript -allmatches

C:\PS> $a
C:\Windows\system32\WindowsPowerShell\v1.0\en-us\about_Pssnapins.help.txt:39:       Start-Transcript and Stop-Transcript.

C:\PS> $b
C:\Windows\system32\WindowsPowerShell\v1.0\en-us\about_Pssnapins.help.txt:39:       Start-Transcript and Stop-Transcript.

C:\PS>> $a.matches
Groups   : {Transcript}
Success  : True
Captures : {Transcript}
Index    : 13
Length   : 10
Value    : Transcript

C:\PS> $b.matches
Groups   : {Transcript}
Success  : True
Captures : {Transcript}
Index    : 13
Length   : 10
Value    : Transcript

Groups   : {Transcript}
Success  : True
Captures : {Transcript}
Index    : 33
Length   : 10
Value    : Transcript

Description
-----------
This example demonstrates the effect of the AllMatches parameter of Select-String. AllMatches finds all pattern matches in a line, instead of just finding the first match in each line.

The first command in the example searches the Windows PowerShell conceptual Help files ("about" Help) for instances of the word "transcript". The second command is identical, except that it uses the AllMatches parameter.

The output of the first command is saved in the $a variable. The output of the second command is saved in the $b variable.

When you display the value of the variables, the default display is identical, as shown in the example output.

However, the fifth and sixth commands display the value of the Matches property of each object. The Matches property of the first command contains just one match (that is, one System.Text.RegularExpressions.Match object), whereas the Matches property of the second command contains objects for both of the matches in the line.

See Also

  • about_Comparison_Operators
  • about_Regular_Expressions


Select-Xml

Finds text in an XML string or document.

Syntax

Select-XML -Content <string[]> [-Xpath] <string> [-Namespace <hashtable>] [<CommonParameters>]

Select-XML [-Path] <string[]> [-Xpath] <string> [-Namespace <hashtable>] [<CommonParameters>]

Select-XML [-Xml] <XmlNode[]> [-Xpath] <string> [-Namespace <hashtable>] [<CommonParameters>]

Description

The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.

Parameters

-Content <string[]>

Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Namespace <hashtable>

Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceValue>}.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path and file names of the XML files to search. Wildcards are permitted.

Required? | true
Position? | 2
Default Value | None
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-Xml <XmlNode[]>

Specifies one or more XML nodes. A Path or XML parameter is required in every command.

An XML document will be processed as a collection of XML nodes. If you pipe an XML document to Select-XML, each document node will be searched separately as it comes through the pipeline.

Required? | true
Position? | 2
Default Value | None
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Xpath <string>

Specifies an XPath search query. The query language is case-sensitive. This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String or System.Xml.XmlNode You can pipe a path or XML node to Select-XML.
Outputs | System.Xml.XmlElement or System.Xml.XmlText

Notes

XPath is a standard language that is designed to identify parts of an XML document. For more information about the XPath language, see the "Selection Filters" section of the "Event Selection" topic in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143608. And, see "XPath Reference" in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=143609.

Example 1

C:\PS>$path = "$env:windir\System32\WindowsPowerShell\v1.0\Types.ps1xml"

C:\PS> select-xml -path $path -xpath "/Types/Type/Members/AliasProperty"

This example searches the Types.ps1xml file for child items of the AliasProperty node.

Example 2

C:\PS>select-xml -path test*.xml, help.xml -xpath "/Tests/Test[1]/Name"

This command uses Select-XML to search in several XML files.

Example 3

C:\PS>[xml]$Types = get-content "$env:windir\System32\WindowsPowerShell\v1.0\Types.ps1xml"

C:\PS> select-xml -xml $Types -xpath "//MethodName"

This example shows how to pipe an XML document to Search-Path.

Example 4

C:\PS>$namespace = @{command="http://schemas.microsoft.com/maml/dev/command/2004/10"; maml="http://schemas.microsoft.com/maml/2004/10"; dev="http://schemas.microsoft.com/maml/dev/2004/10"}

C:\PS> $path = "$env:windir\System32\WindowsPowerShell\V1.0\en-us\*dll-Help.xml"

C:\PS> select-xml -path $path -namespace $namespace -xpath "//command:name"

Text                      Node      Path
----                      ----      ----
Add-Computer              name      C:\Windows\System32\WindowsPowerShell\V...
Add-Content               name      C:\Windows\System32\WindowsPowerShell\V...
Checkpoint-Computer       name      C:\Windows\System32\WindowsPowerShell\V...
Clear-Content             name      C:\Windows\System32\WindowsPowerShell\V...
Clear-EventLog            name      C:\Windows\System32\WindowsPowerShell\V...
...

Description
-----------
This example shows how to use the Select-XML cmdlet to search the Windows PowerShell XML-based cmdlet help files.

The first command creates a hash table that represents the XML namespace and saves it in the $namespace variable.

The second command saves the path to the help files in the $path variable.

The third command uses Select-Xml to search the XML for cmdlet names by finding Command:Name tags anywhere in the files.

Example 5

C:\PS>select-xml -content $xml -xpath "//edition"

C:\PS> $xml = @"
<?xml version="1.0" encoding="utf-8"?>
 <Book>
   <projects>
     <project name="Book1" date="2009-01-20">
       <editions>
          <edition language="English">En.Book1.com</edition>
          <edition language="German">Ge.Book1.Com</edition>
          <edition language="French">Fr.Book1.com</edition>
          <edition language="Polish">Pl.Book1.com</edition>
       </editions>
     </project>
   </projects>
 </Book>
"@

C:\PS> select-xml -content $xml -xpath "//edition"

Text            Node          Path
----            ----          ----
En.Book1.com    edition       InputStream
Ge.Book1.Com    edition       InputStream
Fr.Book1.com    edition       InputStream
Pl.Book1.com    edition       InputStream

C:\PS> $xml | select-xml -xpath "//edition"

Text            Node          Path
----            ----          ----
En.Book1.com    edition       InputStream
Ge.Book1.Com    edition       InputStream
Fr.Book1.com    edition       InputStream
Pl.Book1.com    edition       InputStream

Description
-----------
This example uses the Content parameter of Select-XML to search XML content in a here-string.

The first command saves the here-string in the $xml variable.

The second command uses the Content parameter to specify the XML in the $xml variable.

The third command is equivalent to the second. It uses a pipeline operator (|) to send the XML in the $xml variable to the Select-XML cmdlet.

For more information about here-strings, type about_Quoting_Rules.

See Also

  • ConvertTo-XML


Send-MailMessage

Sends an e-mail message.

Syntax

Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Body] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-DeliveryNotificationOption {<None> | <OnSuccess> | <OnFailure> | <Delay> | <Never>}] [-Encoding <Encoding>] [-Priority {<Normal> | <Low> | <High>}] [-UseSsl] [<CommonParameters>]

Description

The Send-MailMessage cmdlet sends an e-mail message from within Windows PowerShell.

Parameters

-Attachments <string[]>

Specifies the path and file names of files to be attached to the e-mail message. You can use this parameter or pipe the paths and file names to Send-MailMessage.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Bcc <string[]>

Specifies the e-mail addresses that receive a copy of the mail but are not listed as recipients of the message. Enter names (optional) and the e-mail address, such as "Name <someone@example.com>".

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Body <string>

Specifies the body (content) of the e-mail message.

Required? | false
Position? | 3
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-BodyAsHtml

Indicates that the value of the Body parameter contains HTML.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Cc <string[]>

Specifies the e-mail addresses to which a carbon copy (CC) of the e-mail message is sent. Enter names (optional) and the e-mail address, such as "Name <someone@example.com>".

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one from the Get-Credential cmdlet.

Required? | false
Position? | named
Default Value | Current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DeliveryNotificationOption <DeliveryNotificationOptions>

Specifies the delivery notification options for the e-mail message. You can specify multiple values. "None" is the default value. The alias for this parameter is "dno".

The delivery notifications are sent in an e-mail message to the address specified in the value of the To parameter.

Valid values are:

-- None: No notification.

-- OnSuccess: Notify if the delivery is successful.

-- OnFailure: Notify if the delivery is unsuccessful.

-- Delay: Notify if the delivery is delayed.

-- Never: Never notify.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Encoding <Encoding>

Specifies the encoding used for the body and subject. Valid values are ASCII, UTF8, UTF7, UTF32, Unicode, BigEndianUnicode, Default, and OEM. ASCII is the default.

Required? | false
Position? | named
Default Value | ASCII
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-From <string>

Specifies the address from which the mail is sent. Enter a name (optional) and e-mail address, such as "Name <someone@example.com>". This parameter is required.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Priority <MailPriority>

Specifies the priority of the e-mail message. The valid values for this are Normal, High, and Low. Normal is the default.

Required? | false
Position? | named
Default Value | Normal.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SmtpServer <string>

Specifies the name of the SMTP server that sends the e-mail message.

The default value is the value of the $PSEmailServer preference variable. If the preference variable is not set and this parameter is omitted, the command fails.

Required? | false
Position? | 4
Default Value | $PSEmailServer
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Subject <string>

Specifies the subject of the e-mail message. This parameter is required.

Required? | true
Position? | 2
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-To <string[]>

Specifies the addresses to which the mail is sent. Enter names (optional) and the e-mail address, such as "Name <someone@example.com>". This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSsl

Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer to send mail. By default, SSL is not used.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe the path and file names of attachments to Send-MailMessage.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>send-mailmessage -to "User01 <user01@example.com>" -from "User02 <user02@example.com>" -subject "Test mail"

This command sends an e-mail message from User01 to User02.

The mail message has a subject, which is required, but it does not have a body, which is optional. Also, because the SmtpServer parameter is not specified, Send-MailMessage uses the value of the $PSEmailServer preference variable for the SMTP server.

Example 2

C:\PS>send-mailmessage -from "User01 <user01@example.com>" -to "User02 <user02@example.com>", "User03 <user03@example.com>" -subject "Sending the Attachment" -body "Forgot to send the attachment. Sending now." -Attachment "data.csv" -priority High -dno onSuccess, onFailure -smtpServer smtp.fabrikam.com

This command sends an e-mail message with an attachment from User01 to two other users.

It specifies a priority value of "High" and requests a delivery notification by e-mail when the e-mail messages are delivered or when they fail.

Example 3

C:\PS>send-mailmessage -to "User01 <user01@example.com>" -from "ITGroup <itdept@example.com>" -cc "User02 <user02@example.com>" -bcc ITMgr <itmgr@example.com> -subject "Don't forget today's meeting!" -credential domain01\admin01 -useSSL

This command sends an e-mail message from User01 to the ITGroup mailing list with a copy (CC) to User02 and a blind carbon copy (BCC) to the IT manager (ITMgr).

The command uses the credentials of a domain administrator and the UseSSL parameter.


Set-Acl

Changes the security descriptor of a specified resource, such as a file or a registry key.

Syntax

Set-Acl [-Path] <string[]> [-AclObject] <ObjectSecurity> [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Set-Acl cmdlet changes the security descriptor of a specified resource, such as a file or a registry key, to match the values in a security descriptor that you supply.

To use Set-Acl, use the Path parameter to identify the resource whose security descriptor you want to change, and use the AclObject parameter to supply a security descriptor that has the values you want to apply. Set-Acl uses the value of the AclObject parameter as a model and changes the values in the resource's security descriptor to match the values in the AclObject parameter.

Parameters

-AclObject <ObjectSecurity>

Specifies an ACL with the desired property values. Set-Acl changes the ACL of resource specified by the Path parameter to match the values in the specified security object.

You can save the output of a Get-Acl command in a variable and then use the AclObject parameter to pass the variable, or type a Get-Acl command.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Changes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the security descriptor. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Identifies the resource whose security descriptor you want to change. Enter the path to a resource, such as a path to a file or registry key. Wildcards are permitted.

If you pass a security object to Set-Acl (either by using the AclObject parameter or by passing an object from Get-Acl to Set-Acl), and you omit the Path parameter (name and value), Set-Acl uses the path that is included in the security object.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Security.AccessControl.ObjectSecurity You can pipe a security descriptor to Set-Acl.
Outputs | None or security object By default, Set-Acl does not generate any output. However, if you use the -Passthru parameter, it generates a security object. The type of the security object depends on the type of the resource.

Notes

The Set-Acl cmdlet is supported by the Windows PowerShell file system and registry providers. As such, you can use it to change the security descriptors of files, directories, and registry keys.

When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>".

Example 1

C:\PS>$DogACL = get-acl c:\dog.txt

C:\PS>set-acl -path C:\cat.txt -AclObject $DogACL

These commands copy the values from the security descriptor of the Dog.txt file to the security descriptor of the Cat.txt file. When the commands complete, the security descriptors of the Dog.txt and Cat.txt files are identical.

The first command uses the Get-Acl cmdlet to get the security descriptor of the Dog.txt file. The assignment operator (=) stores the security descriptor in the value of the $DogACL variable.

The second command uses Set-Acl to change the values in the ACL of Cat.txt to the values in $DogACL.

The value of the Path parameter is the path to the Cat.txt file. The value of the AclObject parameter is the model ACL, in this case, the ACL of Dog.txt as saved in the $DogACL variable.

Example 2

C:\PS>get-acl c:\dog.txt | set-acl -path C:\cat.txt

This command is almost the same as the command in the previous example, except that it uses a pipeline operator to send the security descriptor retrieved in a Get-Acl command to a Set-Acl command.

The first command uses the Get-Acl cmdlet to get the security descriptor of the Dog.txt file. The pipeline operator (|) passes an object that represents the Dog.txt security descriptor to the Set-Acl command.

The second command uses Set-Acl to apply the security descriptor of  Dog.txt to Cat.txt. When the command completes, the ACLs of the Dog.txt and Cat.txt files are identical.

Example 3

C:\PS>$newACL = get-acl file0.txt

C:\PS>get-childitem c:\temp -recurse -include *.txt -force | set-acl -aclobject $newacl

These commands apply the security descriptors in the File0.txt file to all text files in the C:\Temp directory and all of its subdirectories.

The first command gets the security descriptor of the File0.txt file in the current directory and uses the assignment operator (=) to store it in the $newACL variable.

The first command in the pipeline uses the Get-ChildItem cmdlet to get all of the text files in the C:\Temp directory. The Recurse parameter extends the command to all subdirectories of C:\temp. The Include parameter limits the files retrieved to those with the ".txt" file name extension. The Force parameter gets hidden files, which would otherwise be excluded. (You cannot use "c:\temp\*.txt", because the Recurse parameter works on directories, not on files.)

The pipeline operator (|) sends the objects representing the retrieved files to Set-Acl command, which applies the security descriptor in the AclObject parameter to all of the files in the pipeline.

In practice, it is best to use the Whatif parameter with all Set-Acl commands that can affect more than one resource. In this case, the second command in the pipeline would be "set-acl -aclobject $newacl -whatif". This command lists the files that would be affected by the command. After reviewing the result, you can run the command again without the Whatif parameter.

See Also

  • Get-Acl


Set-Alias

Creates or changes an alias (alternate name) for a cmdlet or other command element in the current Windows PowerShell session.

Syntax

Set-Alias [-Name] <string> [-Value] <string> [-Description <string>] [-Force] [-Option {<None> | <ReadOnly> | <Constant> | <Private> | <AllScope>}] [-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Set-Alias cmdlet creates or changes an alias (alternate name) for a cmdlet or for a command element, such as a function, a script, a file, or other executable. You can also use Set-Alias to reassign a current alias to a new command, or to change any of the properties of an alias, such as its description. Unless you add the alias to the Windows PowerShell profile, the changes to an alias are lost when you exit the session or close Windows PowerShell.

Parameters

-Description <string>

Specifies a description of the alias. You can type any string. If the description includes spaces, enclose it quotation marks.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to set a read-only alias. Use the Option parameter to create a read-only alias. The Force parameter cannot set a constant alias.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies the new alias. You can use any alphanumeric characters in an alias, but the first character cannot be a number.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Option <ScopedItemOptions>

Sets the value of the Options property of the alias.

Valid values are:

-- None: Sets no options. (default)

-- ReadOnly: The properties of the alias cannot be changed, except by using the Force parameter. You can use Remove-Item to delete the alias.

-- Constant: The alias cannot be deleted and its properties cannot be changed. Constant is available only when you are creating an alias. You cannot change the option of an existing alias to Constant.

-- Private: The alias is available only within the scope specified by the Scope parameter. It is invisible in all other scopes.

-- AllScope: The alias is copied to any new scopes that are created.

To see the Options property of the aliases, type "Get-Alias | Format-Table -property Name, Definition, Options -autosize".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the alias. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Scope <string>

Specifies the scope in which this alias is valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Value <string>

Specifies the name of the cmdlet or command element that is being aliased.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs

None

You cannot pipe input to this cmdlet.

Outputs

When you use the PassThru parameter, Set-Alias generates a System.Management.Automation.AliasInfo object representing the alias. Otherwise, this cmdlet does not generate any output.

When you use the PassThru parameter, Set-Alias generates a System.Management.Automation.AliasInfo object representing the alias. Otherwise, this cmdlet does not generate any output.

Notes

An alias is an alternate name or nickname for a cmdlet or command element. To run the cmdlet, you can use its full name or any valid alias. For more information, see about_Aliases.

To create a new alias, use Set-Alias or New-Alias. To delete an alias, use Remove-Item.

A cmdlet can have multiple aliases, but an alias can only be associated with one cmdlet at a time. If you use set-alias to associate the alias with a different cmdlet, it is no longer associated with the original cmdlet.

You can create an alias for a cmdlet, but you cannot create an alias for a command with parameters and values. For example, you can create an alias for Set-Location, but you cannot create an alias for "Set-Location C:\Windows\System32". To create an alias for a command, create a function that includes the command, and then create an alias to the function.

To save the aliases from a session and use them in a different session, add the set-alias command to your Windows PowerShell profile. Profiles do not exist by default. To create a profile in the path stored in the $profile variable, type "New-Item -type file -force $profile". To see the value of the $profile variable, type "$profile".

You can also save your aliases by using Export-Alias to copy the aliases from the session to a file, and then use Import-Alias to add them to the alias list for a new session.

You can also refer to Set-Alias by its built-in alias, "sal". For more information, see about_Aliases.

Example 1

C:\PS>set-alias -name list -value get-childitem

This command creates the alias "list" for the Get-ChildItem cmdlet. After you create the alias, you can use "list" in place of "Get-ChildItem" at the command line and in scripts.

Example 2

C:\PS>set-alias list get-location

This command associates the alias "list" with the Get-Location cmdlet. If "list" is an alias for another cmdlet, this command changes its association so that it now is the alias only for Get-Location.

This command uses the same format as the command in the previous example, but it omits the optional parameter names, -Name and -Value. When you omit parameter names, the values of those parameters must appear in the specified order in the command. In this case, the value of -Name ("list") must be the first parameter and the value of -Value ("get-location") must be the second parameter.

Example 3

C:\PS>set-alias scrub remove-item -option readonly -passthru | format-list

This command associates the alias "scrub" with the Remove-Item cmdlet. It uses the "ReadOnly" option to prevent the alias from being deleted or assigned to another cmdlet.

The PassThru parameter directs Windows PowerShell to pass an object that represents the new alias through the pipeline to the Format-List cmdlet. If the PassThru parameter were omitted, there would be no output from this cmdlet to display (in a list or otherwise).

Example 4

C:\PS>Set-Alias np c:\windows\notepad.exe

This command associates the alias, "np", with the executable file for Notepad. After the command completes, to open Notepad from the Windows PowerShell command line, just type "np".

This example demonstrates that you can create aliases for executable files and elements other than cmdlets.

To make the command more generic, you can use the "Windir" environment variable (${env:windir}) to represent the C\Windows directory. The generic version of the command is "set-alias np ${env:windir}\notepad.exe".

Example 5

C:\PS>function CD32 {set-location c:\windows\system32}

C:\PS>set-alias go cd32

These commands show how to assign an alias to a command with parameters, or even to a pipeline of many commands.

You can create an alias for a cmdlet, but you cannot create an alias for a command that consists of a cmdlet and its parameters. However, if you place the command in a function or a script, then you can create a useful function or script name and you can create one or more aliases for the function or script.

In this example, the user wants to create an alias for the command "set-location c:\windows\system32", where "set-location" is a cmdlet and "C:\Windows\System32" is the value of the Path parameter.

To do this, the first command creates a function called "CD32" that contains the Set-Location command.

The second command creates the alias "go" for the CD32 function. Then, to run the Set-Location command, the user can type either "CD32" or "go".

See Also

  • Get-Alias
  • New-Alias
  • Export-Alias
  • Import-Alias


Set-AuthenticodeSignature

Adds an Authenticode signature to a Windows PowerShell script or other file.

Syntax

Set-AuthenticodeSignature [-FilePath] <string[]> [-Certificate] <X509Certificate2> [-Force] [-HashAlgorithm <string>] [-IncludeChain <string>] [-TimestampServer <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Set-AuthenticodeSignature cmdlet adds an Authenticode signature to any file that supports Subject Interface Package (SIP).

In a Windows PowerShell script file, the signature takes the form of a block of text that indicates the end of the instructions that are executed in the script. If there is a signature in the file when this cmdlet runs, that signature is removed.

Parameters

-Certificate <X509Certificate2>

Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate.

To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have code-signing authority, the command fails.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilePath <string[]>

Specifies the path to a file that is being signed.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to append a signature to a read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-HashAlgorithm <string>

Specifies the hashing algorithm that Windows uses to compute the digital signature for the file. The default is SHA1, which is the Windows default hashing algorithm.

Files that are signed with a different hashing algorithm might not be recognized on other systems.

Required? | false
Position? | named
Default Value | SHA1
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-IncludeChain <string>

Determines which certificates in the certificate trust chain are included in the digital signature. "NotRoot" is the default.

Valid values are:

-- Signer: Includes only the signer's certificate.

-- NotRoot: Includes all of the certificates in the certificate chain, except for the root authority.

--All: Includes all the certificates in the certificate chain.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-TimestampServer <string>

Uses the specified time stamp server to add a time stamp to the signature. Type the URL of the time stamp server as a string.

The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the certificate expires because users and programs can verify that the certificate was valid at the time of signing.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains the file path to Set-AuthenticodeSignature.
Outputs | System.Management.Automation.Signature

Example 1

C:\PS>$cert=Get-ChildItem -Path cert:\CurrentUser\my -CodeSigningCert

C:\PS>Set-AuthenticodeSignature -FilePath PsTestInternet2.ps1 -certificate $cert

These commands retrieve a code-signing certificate from the Windows PowerShell certificate provider and use it to sign a Windows PowerShell script.

The first command uses the Get-ChildItem cmdlet and the Windows PowerShell certificate provider to get the certificates in the Cert:\CurrentUser\My subdirectory of the certificate store. (The Cert: drive is the drive exposed by the certificate provider.) The CodeSigningCert parameter, which is supported only by the certificate provider, limits the certificates retrieved to those with code-signing authority. The command stores the result in the $cert variable.

The second command uses the Set-AuthenticodeSignature cmdlet to sign the PSTestInternet2.ps1 script. It uses the FilePath parameter to specify the name of the script and the Certificate parameter to specify that the certificate is stored in the $cert variable.

Example 2

C:\PS>$cert = Get-PfxCertificate C:\Test\Mysign.pfx

C:\PS>Set-AuthenticodeSignature -Filepath ServerProps.ps1 -Cert $cert

These commands use the Get-PfxCertificate cmdlet to find a code signing certificate. Then, they use it to sign a Windows PowerShell script.

The first command uses the Get-PfxCertificate cmdlet to find the C:\Test\MySign.pfx certificate and store it in the $cert variable.

The second command uses Set-AuthenticodeSignature to sign the script. The FilePath parameter of Set-AuthenticodeSignature specifies the path to the script file being signed and the Cert parameter passes the $cert variable containing the certificate to Set-AuthenticodeSignature.

If the certificate file is password protected, Windows PowerShell prompts you for the password.

Example 3

C:\PS>Set-AuthenticodeSignature -filepath c:\scripts\Remodel.ps1 -certificate $cert -IncludeChain All -TimeStampServer "http://timestamp.fabrikam.com/scripts/timstamper.dll"

This command adds a digital signature that includes the root authority in the trust chain, and it is signed by a third-party timestamp server.

The command uses the FilePath parameter to specify the script being signed and the Certificate parameter to specify the certificate that is saved in the $cert variable. It uses the IncludeChain parameter to include all of the signatures in the trust chain (including the root authority). It also uses the TimeStampServer parameter to add a timestamp to the signature. This prevents the script from failing when the certificate expires.

See Also

  • about_Signing
  • about_Execution_Policies
  • Get-AuthenticodeSignature
  • Get-PfxCertificate
  • Get-ExecutionPolicy
  • Set-ExecutionPolicy


Set-Content

Writes or replaces the content in an item with new content.

Syntax

Set-Content [-LiteralPath] <string[]> [-Value] <Object[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Set-Content [-Path] <string[]> [-Value] <Object[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Set-Content cmdlet is a string-processing cmdlet that writes or replaces the content in the specified item, such as a file. Whereas the Add-Content cmdlet appends content to a file, Set-Content replaces the existing content. You can type the content in the command or send content through the pipeline to Set-Content.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to set the contents of a file, even if the file is read-only. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Changes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the path to the item that will receive the content. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the content. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the item that will receive the content. Wildcards are permitted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Value <Object[]>

Specifies the new content for the item.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Object You can pipe an object that contains the new value for the item to Set-Content.
Outputs | None or System.String When you use the Passthru parameter, Set-Content generates a System.String object representing the content. Otherwise, this cmdlet does not generate any output.

Notes

You can also refer to Set-Content by its built-in alias, "sc". For more information, see about_Aliases.

Set-Content is designed for string processing. If you pipe non-string objects to Set-Content, it converts the object to a string before writing it. To write objects to files, use Out-File.

The Set-Content cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>set-content -path C:\Test1\test*.txt -value "Hello, World"

This command replaces the contents of all files in the Test1 directory that have names beginning with "test" with "Hello, World". This example shows how to specify content by typing it in the command.

Example 2

C:\PS>get-date | set-content C:\Test1\date.csv

This command creates a comma-separated variable-length (csv) file that contains only the current date and time. It uses the Get-Date cmdlet to get the current system date and time. The pipeline operator passes the result to Set-Content, which creates the file and writes the content.

If the Test1 directory does not exist, the command fails, but if the file does not exist, the command will create it.

Example 3

C:\PS>(get-content Notice.txt) | foreach-object {$_ -replace "Warning", "Caution"} | set-content Notice.txt

This command replaces all instances of "Warning" with "Caution" in the Notice.txt file.

It uses the Get-Content cmdlet to get the content of Notice.txt. The pipeline operator sends the results to the ForEach-Object cmdlet, which applies the expression to each line of content in Get-Content. The expression uses the "$_" symbol to refer to the current item and the Replace parameter to specify the text to be replaced.

Another pipeline operator sends the changed content to Set-Content which replaces the text in Notice.txt with the new content.

The parentheses around the Get-Content command ensure that the Get operation is complete before the Set operation begins. Without them, the command will fail because the two functions will be trying to access the same file.

See Also

  • about_Providers
  • Add-Content
  • Get-Content
  • Clear-Content


Set-Date

Changes the system time on the computer to a time that you specify.

Syntax

Set-Date [-Adjust] <TimeSpan> [-DisplayHint {<Date> | <Time> | <DateTime>}] [-Confirm] [-WhatIf] [<CommonParameters>]

Set-Date [-Date] <DateTime> [-DisplayHint {<Date> | <Time> | <DateTime>}] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Set-Date cmdlet changes the system date and time on the computer to a date and time that you specify. You can specify a new date and/or time by typing a string or by passing a DateTime or TimeSpan object to Set-Date. To specify a new date or time, use the Date parameter. To specify a change interval, use the Adjust parameter.

Parameters

-Adjust <TimeSpan>

Adds or subtracts the specified value from the current date and time. You can type an adjustment in standard date and time format for your locale or use the Adjust parameter to pass a TimeSpan object from New-TimeSpan to Set-Date.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Date <DateTime>

Changes the date and time to the specified values. You can type a new date in the short date format and a time in the standard time format for your locale. Or, you can pass a Date-Time object from Get-Date.

If you specify a date, but not a time, Set-Date changes the time to midnight on the specified date. If you specify only a time, it does not change the date.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-DisplayHint <DisplayHintType>

Determines which elements of the date and time are displayed.

Valid values are:

-- date: displays only the date

-- time: displays only the time

-- datetime: displays the date and time

This parameter affects only the display. It does not affect the DateTime object that Get-Date retrieves.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.DateTime You can pipe a date to Set-Date.
Outputs | System.DateTime Set-Date returns an object that represents the date that it set.

Notes

Use this cmdlet cautiously. Changing the date and time on the computer. The change might prevent the computer from receiving system-wide events and updates that are triggered by a date or time. Use the -WhatIf and -Confirm parameters to avoid errors.

You can use standard .NET methods with the DateTime and TimeSpan objects used with Set-Date, such as AddDays, AddMonths and FromFileTime. For more information, see "DateTime Methods" and "TimeSpan Methods."

Example 1

C:\PS>Set-Date -Date (Get-Date).AddDays(3)

This command adds three days to the current system date. It does not affect the time. The command uses the Date parameter to specify the date. It uses the Get-Date cmdlet to get the current date and time and applies the AddDays .NET method for DateTime objects with a value of 3 (days).

Example 2

C:\PS>set-date -adjust -0:10:0 -displayHint time

This command sets the current system time back by 10 minutes. It uses the Adjust parameter to specify an interval of change and the time change (minus ten minutes) in standard time format for the locale. The DisplayHint parameter tells Windows PowerShell to display only the time, but it does not affect the DateTime object that Set-Date returns.

Example 3

C:\PS>$t = get-date

C:\PS>set-date -date $t

These commands change the system date and time on the computer to the date and time saved in the variable $t. The first command gets the date and stores it in $t. The second command uses the Date parameter to pass the DateTime object in $t to the Set-Date cmdlet.

Example 4

C:\PS>$90mins = new-timespan -minutes 90

C:\PS>set-date -adjust $90mins

These commands advance the system time on the local computer by 90 minutes. The first command uses the New-Timespan cmdlet to create a TimeSpan object with a 90-minute interval, and then it saves the TimeSpan object in the $90mins variable. The second command uses the Adjust parameter of Set-Date to adjust the date by the value of the TimeSpan object in the $90mins variable.

See Also

  • Get-Date
  • New-TimeSpan


Set-ExecutionPolicy

Changes the user preference for the Windows PowerShell execution policy.

Syntax

Set-ExecutionPolicy [-ExecutionPolicy] {<Unrestricted> | <RemoteSigned> | <AllSigned> | <Restricted> | <Default> | <Bypass> | <Undefined>} [[-Scope] {<Process> | <CurrentUser> | <LocalMachine> | <UserPolicy> | <MachinePolicy>}] [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Set-ExecutionPolicy changes the user preference for the Windows PowerShell execution policy.

To run this command on Windows Vista, Windows Server 2008, and later versions of Windows, you must start Windows PowerShell with the "Run as administrator" option, even if you are a member of the Administrators group on the computer.

The execution policy is part of the security strategy of Windows PowerShell. It determines whether you can load configuration files (including your Windows PowerShell profile) and run scripts, and it determines which scripts, if any, must be digitally signed before they will run.

For more information, see about_Execution_Policies.

Parameters

-ExecutionPolicy <ExecutionPolicy>

Specifies a new execution policy for the shell. The parameter name ("Name") is optional.

Valid values are:

-- Restricted: Does not load configuration files or run scripts. "Restricted" is the default.

-- AllSigned: Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on the local computer.

-- RemoteSigned: Requires that all scripts and configuration files downloaded from the Internet be signed by a trusted publisher.

-- Unrestricted: Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs.

-- Bypass: Nothing is blocked and there are no warnings or prompts.

-- Undefined: Removes the currently assigned execution policy from the current scope. This parameter will not remove an execution policy that is set in a Group Policy scope.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Force

Suppresses all prompts. By default, Set-ExecutionPolicy displays a warning whenever you change the execution policy.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Scope <ExecutionPolicyScope>

Specifies the scope of the execution policy. The default is LocalMachine.

Valid values are:

-- Process: The execution policy affects only the current Windows PowerShell process.

-- CurrentUser: The execution policy affects only the current user.

-- LocalMachine: The execution policy affects all users of the computer.

To remove an execution policy from a particular scope, set the execution policy for that scope to Undefined.

Required? | false
Position? | 2
Default Value | LocalMachine
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | Microsoft.PowerShell.ExecutionPolicy, System.String You can pipe an execution policy object or a string that contains the name of an execution policy to Set-ExecutionPolicy.
Outputs | None This cmdlet does not return any output.

Notes

When you use Set-ExecutionPolicy, the new user preference is written to the registry and remains unchanged until you change it.

However, if the "Turn on Script Execution" Group Policy is enabled for the computer or user, the user preference is written to the registry, but it is not effective, and Windows PowerShell displays a message explaining the conflict. You cannot use Set-ExecutionPolicy to override a Group Policy, even if the user preference is more restrictive than the policy.

Example 1

C:\PS>set-executionpolicy remotesigned

This command sets the user preference for the shell execution policy to RemoteSigned.

Example 2

C:\PS>Set-ExecutionPolicy Restricted

Set-ExecutionPolicy : Windows PowerShell updated your local preference successfully, but the setting is overridden by the group policy applied to your system. Due to the override, your shell will retain its current effective execution policy of "AllSigned". Contact your group policy administrator for more information.
At line:1 char:20
+ set-executionpolicy  <<<< restricted

Description
-----------
This command attempts to set the execution policy for the shell to "Restricted." The "Restricted" setting is written to the registry, but because it conflicts with a Group Policy, it is not effective, even though it is more restrictive than the policy.

Example 3

C:\PS>invoke-command -computername Server01 -scriptblock {get-executionpolicy} | set-executionpolicy -force

This command gets the execution policy from a remote computer and applies that execution policy to the local computer.

The command uses the Invoke-Command cmdlet to send the command to the remote computer. Because you can pipe an ExecutionPolicy (Microsoft.PowerShell.ExecutionPolicy) object to Set-ExecutionPolicy, the Set-ExecutionPolicy command does not need an ExecutionPolicy parameter.

The command does have a Force parameter, which suppresses the user prompt.

Example 4

C:\PS>set-executionpolicy -scope CurrentUser -executionPolicy AllSigned -force

C:\PS> get-executionpolicy -list

        Scope   ExecutionPolicy
        -----   ---------------
MachinePolicy         Undefined
   UserPolicy         Undefined
      Process         Undefined
  CurrentUser         AllSigned
 LocalMachine      RemoteSigned

C:\PS> get-executionpolicy
AllSigned

Description
-----------
This example shows how to set an execution policy for a particular scope.

The first command uses the Set-ExecutionPolicy cmdlet to set an execution policy of AllSigned for the current user. It uses the Force parameter to suppress the user prompts.

The second command uses the List parameter of Get-ExecutionPolicy to get the execution policies set in each scope. The results show that the execution policy that is set for the current user differs from the execution policy set for all users of the computer.

The third command uses the Get-ExecutionPolicy cmdlet without parameters to get the effective execution policy for the current user on the local computer. The result confirms that the execution policy that is set for the current user takes precedence over the one set for all users.

Example 5

C:\PS>set-executionpolicy -scope CurrentUser -executionPolicy Undefined

This command uses an execution policy value of Undefined to effectively remove the execution policy that is set for the current user scope. As a result, the execution policy that is set in Group Policy or in the LocalMachine (all users) scope is effective.

If you set the execution policy in all scopes to Undefined and the Group Policy is not set, the default execution policy, Restricted, is effective for all users of the computer.

See Also

  • Get-ExecutionPolicy
  • Set-AuthenticodeSignature
  • Get-AuthenticodeSignature
  • about_Execution_Policies
  • about_Signing


Set-Item

Changes the value of an item to the value specified in the command.

Syntax

Set-Item [-LiteralPath] <string[]> [[-Value] <Object>] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Set-Item [-Path] <string[]> [[-Value] <Object>] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Set-Item cmdlet changes the value of an item, such as a variable or registry key, to the value specified in the command.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to set items that cannot otherwise be changed, such as read-only alias or variables. The cmdlet cannot change constant aliases or variables. Implementation varies from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Changes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the location of the new items. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Passes an object representing the item to the pipeline. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies a path to the location of the new items. Wildcards are permitted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Value <Object>

Specifies a new value for the item.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Object You can pipe an object that represents the new value of the item to Set-Item.
Outputs | None or an object representing the new or changed item. When you use the Passthru parameter, Set-Item generates an object representing the item. Otherwise, this cmdlet does not generate any output.

Notes

You can also refer to Set-Item by its built-in alias, "si". For more information, see about_Aliases.

The Set-Item cmdlet is not supported by the Windows PowerShell FileSystem Provider. To change the values of items in the file system, use Set-Content.

In the Registry drives, HKLM: and HKCU:, Set-Item changes the data in the (Default) value of a registry key. To create and change the names of registry keys, use New-Item and Rename-Item. To change the names and data in registry values, use New-ItemProperty, Set-ItemProperty, and Rename-ItemProperty.

The Set-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PsProvider". For more information, see about_Providers.

Example 1

C:\PS>set-item -path alias:np -value c:\windows\notepad.exe

This command creates an alias of "np" for Notepad.

Example 2

C:\PS>set-item -path env:UserRole -value Administrator

This command uses the Set-Item cmdlet to change the value of the "UserRole" environment variable to "Administrator".

Example 3

C:\PS>set-item -path function:prompt -value {'PS '+ $(Get-Date -format t) + " " + $(Get-Location) + '> '}

This command uses the Set-Item cmdlet to change the "prompt" function so that it displays the time before the path.

Example 4

C:\PS>set-item -path function:prompt -options "AllScope,ReadOnly"

This command sets the AllScope and ReadOnly options for the "prompt" function. This command uses the Options dynamic parameter of the Set-Item cmdlet. The Options parameter is available in Set-Item only when you use it with the Alias or Function provider.

See Also

  • about_Providers
  • Get-Item
  • New-Item
  • Remove-Item
  • Clear-Item
  • Invoke-Item
  • Rename-Item
  • Move-Item
  • Copy-Item


Set-ItemProperty

Creates or changes the value of a property of an item.

Syntax

Set-ItemProperty [-LiteralPath] <string[]> -InputObject <psobject> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Set-ItemProperty [-Path] <string[]> -InputObject <psobject> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Set-ItemProperty [-LiteralPath] <string[]> [-Name] <string> [-Value] <Object> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Set-ItemProperty [-Path] <string[]> [-Name] <string> [-Value] <Object> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

Description

The Set-ItemProperty cmdlet changes the value of the property of the specified item. You can use the cmdlet to establish or change the properties of items. For example, you can use Set-ItemProperty to set the value of the IsReadOnly property of a file object to true.

You also use Set-ItemProperty to create and change registry values and data. For example, you can add a new registry entry to a key and establish or change its value.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Specifies those items upon which the cmdlet is not to act, and includes all others.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to set a property on items that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see about_Providers.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Specifies only those items upon which the cmdlet will act, excluding all others.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the object that has the properties that you want to change. Enter a variable that contains the object or a command that gets the object.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Name <string>

Specifies the name of the property.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the item property. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the path to the items with the property to be set.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Value <Object>

Specifies the value of the property.

Required? | true
Position? | 3
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe objects to Set-ItemProperty.
Outputs | None or System.Management.Automation.PSCustomObject When you use the PassThru parameter, Set-ItemProperty generates a PSCustomObject object that represents the item that was changed and its new property value. Otherwise, this cmdlet does not generate any output.

Notes

The Set-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>set-itemproperty -path c:\GroupFiles\final.doc -name IsReadOnly -value $true

This command sets the value of the IsReadOnly property of the final.doc file to true.

The command uses the Set-ItemProperty cmdlet to change the value of the property of the final.doc file. It uses the Path parameter to specify the file. It uses the Name parameter to specify the name of the property and the Value parameter to specify the new value.

The $true automatic variable represents a value of TRUE. For more information, see about_Automatic_Variables.

The file is a System.IO.FileInfo object and IsReadOnly is just one of its properties. To see all of the properties and methods of a FileInfo object, pipe the file to the Get-Member cmdlet. For example, "final.doc | get-member".

Example 2

C:\PS>set-itemproperty -path HKLM:\Software\MyCompany -name NoOfEmployees -value 823

C:\PS>get-itemproperty -path HKLM:\Software\MyCompany

PSPath        : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany
PSParentPath  : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software
PSChildName   : mycompany
PSDrive       : HKLM
PSProvider    : Microsoft.PowerShell.Core\Registry
NoOfLocations : 2
NoOfEmployees : 823

C:\PS>set-itemproperty -path HKLM:\Software\MyCompany -name NoOfEmployees -value 824
C:\PS>get-itemproperty -path HKLM:\Software\MyCompany

PSPath        : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany
PSParentPath  : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software
PSChildName   : mycompany
PSDrive       : HKLM
PSProvider    : Microsoft.PowerShell.Core\Registry
NoOfLocations : 2
NoOfEmployees : 824

Description
-----------
This example shows how to use Set-ItemProperty to create a new registry entry and to assign a value to the entry. It creates the NoOfEmployees entry in the MyCompany key in HKLM\Software key and sets its value to 823.

Because registry entries are considered to be properties of the registry keys (which are items), you use Set-ItemProperty to create registry entries, and to establish and change their values.

The first command uses the Set-ItemProperty cmdlet to create the registry entry. It uses the Path parameter to specify the path to the HKLM: drive and the Software\MyCompany key. It uses the Name parameter to specify the entry name and the Value parameter to specify a value.

The second command uses the Get-ItemProperty cmdlet to see the new registry entry. If you use the Get-Item or Get-ChildItem cmdlets, the entries do not appear because they are properties of a key, not items or child items.

The third command changes the value of the NoOfEmployees entry to 824.

You can also use the New-ItemProperty cmdlet to create the registry entry and its value and then use Set-ItemProperty to change the value.

For more information about the HKLM: drive, type "get-help get-psdrive". For more information about using Windows PowerShell to manage the registry, type "get-help registry".

Example 3

C:\PS>get-childitem weekly.txt | set-itemproperty -name IsReadOnly -value $true

These commands show how to use a pipeline operator (|) to send an item to Set-ItemProperty.

The first part of the command uses the Get-ChildItem cmdlet to get an object that represents the Weekly.txt file. The command uses a pipeline operator to send the file object to Set-ItemProperty. The Set-ItemProperty command uses the Name and Value parameters to specify the property and its new value.

This command is equivalent to using the InputObject parameter to specify the object that Get-ChildItem gets.

See Also

  • about_Providers
  • Get-ItemProperty
  • New-ItemProperty
  • Clear-ItemProperty
  • Remove-ItemProperty
  • Rename-ItemProperty
  • Move-ItemProperty
  • Copy-ItemProperty


Set-Location

Sets the current working location to a specified location.

Syntax

Set-Location [-LiteralPath] <string> [-PassThru] [-UseTransaction] [<CommonParameters>]

Set-Location [[-Path] <string>] [-PassThru] [-UseTransaction] [<CommonParameters>]

Set-Location [-StackName <string>] [-PassThru] [-UseTransaction] [<CommonParameters>]

Description

The Set-Location cmdlet sets the working location to a specified location. That location could be a directory, a sub-directory, a registry location, or another location stack.

Parameters

-LiteralPath <string>

Specifies a path to the location. The value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Passes an object representing the location to the pipeline. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

This parameter is used to specify the path to a new working location.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-StackName <string>

The name of the stack to which the location is being set.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path (but not a literal path) to Set-Location.
Outputs | None or System.Management.Automation.PathInfo When you use the PassThru parameter, Set-Location generates a System.Management.Automation.PathInfo object that represents the location. Otherwise, this cmdlet does not generate any output.

Notes

The Set-Location cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>set-location HKLM:

This will set the current location to the one specified; in this case, it is the HKLM provider.

Example 2

C:\PS>set-location env: -passthru

Path
----
Env:\

Description
-----------
This will set the current location to the one specified; in this case, it is the environment variable provider.

Example 3

C:\PS>set-location C:

This will set the current location to the one specified; in this case, it is the C: drive in the file system provider.

See Also

  • about_Providers
  • Get-Location
  • Pop-Location
  • Push-Location


Set-PSBreakpoint

Sets a breakpoint on a line, command, or variable.

Syntax

Set-PSBreakpoint -Command <string[]> [[-Script] <string[]>] [-Action <scriptblock>] [<CommonParameters>]

Set-PSBreakpoint [-Script] <string[]> [-Line] <Int32[]> [[-Column] <int>] [-Action <scriptblock>] [<CommonParameters>]

Set-PSBreakpoint -Variable <string[]> [[-Script] <string[]>] [-Mode {<Read> | <Write> | <ReadWrite>}] [-Action <scriptblock>] [<CommonParameters>]

Description

The Set-PSBreakpoint cmdlet sets a breakpoint in a script or in any command run in the current session. You can use Set-PSBreakpoint to set a breakpoint before executing a script or running a command, or during debugging, when stopped at another breakpoint.

Note: Set-PSBreakpoint cannot set a breakpoint on a remote computer. To debug a script on a remote computer, copy the script to the local computer and then debug it locally.

Each Set-PSBreakpoint command creates one of the following three types of breakpoints:

-- Line breakpoint: Sets breakpoints at particular line and column coordinates.

-- Command breakpoint: Sets breakpoints on commands and functions.

-- Variable breakpoint: Sets breakpoints on variables.

You can set a breakpoint on multiple lines, commands, or variables in a single Set-PSBreakpoint command, but each Set-PSBreakpoint command sets only one type of breakpoint.

At a breakpoint, Windows PowerShell temporarily stops executing and gives control to the debugger. The command prompt changes to "DBG>", and a set of debugger commands become available for use. However, you can use the Action parameter to specify an alternate response, such as conditions for the breakpoint or instructions to perform additional tasks such as logging or diagnostics.

The Set-PSBreakpoint cmdlet is one of several cmdlets designed for debugging Windows PowerShell scripts. For more information about the Windows PowerShell debugger, see about_Debuggers.

Parameters

-Action <scriptblock>

Specifies commands that run at each breakpoint instead of breaking. Enter a script block that contains the commands. You can use this parameter to set conditional breakpoints or to perform other tasks, such as testing or logging.

If this parameter is omitted, or no action is specified, execution stops at the breakpoint, and the debugger starts.

When the Action parameter is used, the Action script block runs at each breakpoint. Execution does not stop unless the script block includes the Break keyword. If you use the Continue keyword in the script block, execution resumes until the next breakpoint.

For more information, see about_Script_Blocks, about_Break, and about_Continue.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Column <int>

Specifies the column number of the column in the script file on which execution stops. Enter only one column number. The default is column 1.

The Column value is used with the value of the Line parameter to specify the breakpoint. If the Line parameter specifies multiple lines, the Column parameter sets a breakpoint at the specified column on each of the specified lines. Windows PowerShell stops executing before the statement or expression that includes the character at the specified line and column position.

Columns are counted from the top left margin beginning with column number 1 (not 0). If you specify a column that does not exist in the script, an error is not declared, but the breakpoint is never executed.

Required? | false
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Command <string[]>

Sets a command breakpoint. Enter command names, such as "Get-Process" or function names. Wildcards are permitted.

Execution stops just before each instance of each command is executed. If the command is a function, execution stops each time the function is called and at each BEGIN, PROCESS, and END section.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Line <Int32[]>

Sets a line breakpoint in a script. Enter one or more line numbers, separated by commas. Windows PowerShell stops immediately before executing the statement that begins on each of the specified lines.

Lines are counted from the top left margin of the script file beginning with line number 1 (not 0). If you specify a blank line, execution stops before the next non-blank line. If the line is out of range, the breakpoint is never hit.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Mode <VariableAccessMode>

Determines the mode of access that triggers variable breakpoints. The default is Write.

This parameter is valid only when the Variable parameter is used in the command. The mode applies to all breakpoints set in the command.

Valid values are:

-- Write: Stops execution immediately before a new value is written to the variable.

-- Read: Stops execution when the variable is read, that is, when its value is accessed, either to be assigned, displayed, or used. In read mode, execution does not stop when the value of the variable changes.

-- ReadWrite: Stops execution when the variable is read or written.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Script <string[]>

Sets a breakpoint in each of the specified script files. Enter the paths and file names of one or more script files. If the files are in the current directory, you can omit the path. Wildcards are permitted.

By default, variable breakpoints and command breakpoints are set on any command that runs in the current session. This parameter is required only when setting a line breakpoint.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Variable <string[]>

Sets a variable breakpoint. Enter a comma-separated list of variables without dollar signs ($).

Use the Mode parameters to determine the mode of access that triggers the breakpoints. The default mode, Write, stops execution just before a new value is written to the variable.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to Set-PSBreakpoint.
Outputs | Breakpoint object (System.Management.Automation.LineBreakpoint, System.Management.Automation.VariableBreakpoint, System.Management.Automation.CommandBreakpoint) Set-PSBreakpoint returns an object that represents each breakpoint that it sets.

Notes

Set-PSBreakpoint cannot set a breakpoint on a remote computer. To debug a script on a remote computer, copy the script to the local computer and then debug it locally.

When you set a breakpoint on more than one line, command, or variable, Set-PSBreakpoint generates a breakpoint object for each entry.

When setting a breakpoint on a function or variable at the command prompt, you can set the breakpoint before or after you create the function or variable.

Example 1

C:\PS>set-psbreakpoint -script sample.ps1 -line 5

Column     : 0
Line       : 5
Action     :
Enabled    : True
HitCount   : 0
Id         : 0
Script     : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1

Description
-----------
This command sets a breakpoint at line 5 in the Sample.ps1 script. As a result, when the script runs, execution stops immediately before line 5 would execute.

When you set a new breakpoint by line number, the Set-PSBreakpoint cmdlet generates a line breakpoint object (System.Management.Automation.LineBreakpoint) that includes the breakpoint ID and hit count, as shown in the following sample output.

Example 2

C:\PS>set-psbreakpoint -command Increment -script sample.ps1

Command    : Increment
Action     :
Enabled    : True
HitCount   : 0
Id         : 1
Script     : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1

Description
-----------
This command creates a command breakpoint on the Increment function in the Sample.ps1 cmdlet. The script stops executing immediately before each call to the specified function.

The result is a command breakpoint object. Before the script runs, the value of the HitCount property is 0.

Example 3

C:\PS>set-psbreakpoint -script sample.ps1 -variable Server -Mode ReadWrite

This command sets a breakpoint on the Server variable in the Sample.ps1 script. It uses the Mode parameter with a value of ReadWrite to stop execution when the value of the variable is read and just before the value changes.

Example 4

C:\PS>set-psbreakpoint -script Sample.ps1 -command "write*"

This command sets a breakpoint on every command in the Sample.ps1 script that begins with "write", such as "write-host".

Example 5

C:\PS>set-psbreakpoint -script test.ps1 -command DiskTest `
  -action { (if $disk -gt 2) { break } }

This command stops execution at the DiskTest function in the Test.ps1 script only when the value of the $disk variable is greater than 2.

It uses the Set-PSBreakpoint cmdlet to set a command breakpoint on the DiskTest function. The value of the action is a script block that tests the value of the $disk variable in the function.

The action uses the BREAK keyword to stop execution if the condition is met. The alternative (and the default) is CONTINUE.

Example 6

C:\PS>set-psbreakpoint -command checkpoint-computer

Id       : 0
Command  : checkpoint-computer
Enabled  : True
HitCount : 0
Action   :

C:\PS> function CheckLog {
>> get-eventlog -log Application |
>> where {($_.source -like "TestApp") -and ($_.Message -like "*failed*")}
>>}
>>
C:\PS> Checklog
DEBUG: Hit breakpoint(s)
DEBUG:  Function breakpoint on 'prompt:Checklog'
C:\PS>>>

Description
-----------
This command sets a breakpoint on the CheckLog function. Because the command does not specify a script, the breakpoint is set on anything that runs in the current session. The debugger breaks when the function is called, not when it is declared.

Example 7

C:\PS>set-psbreakpoint -script sample.ps1 -line 1, 14, 19 -column 2 -action {&(log.ps1)}

Column     : 2
Line       : 1
Action     :
Enabled    : True
HitCount   : 0
Id         : 6
Script     : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1

Column     : 2
Line       : 14
Action     :
Enabled    : True
HitCount   : 0
Id         : 7
Script     : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1

Column     : 2
Line       : 19
Action     :
Enabled    : True
HitCount   : 0
Id         : 8
Script     : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1

Description
-----------
This command sets three line breakpoints in the Sample.ps1 script. It sets one breakpoint at column 2 on each of the lines specified in the script. The action specified in the Action parameter applies to all breakpoints.

See Also

  • about_Debuggers
  • Get-PSBreakpoint
  • Enable-PSBreakpoint
  • Disable-PSBreakpoint
  • Remove-PSBreakpoint
  • Get-PSCallStack


Set-PSDebug

Turns script debugging features on and off, sets the trace level, and toggles strict mode.

Syntax

Set-PSDebug [-Off] [<CommonParameters>]

Set-PSDebug [-Step] [-Strict] [-Trace <int>] [<CommonParameters>]

Description

The Set-PSDebug cmdlet turns script debugging features on and off, sets the trace level, and toggles strict mode.

When the Trace parameter is set to 1, each line of script is traced as it is executed. When the parameter is set to 2, variable assignments, function calls, and script calls are also traced. If the Step parameter is specified, you are prompted before each line of the script is executed.

Parameters

-Off

Turns off all script debugging features.

Note: A "Set-StrictMode -off" command disables the verification set by a "set-psdebug -strict" command. For more information, see Set-StrictMode.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Step

Turns on script stepping. Before each line is run, the user is prompted to stop, continue, or enter a new interpreter level to inspect the state of the script.

Note: Specifying the Step parameter automatically sets a Trace level of 1.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Strict

Specifies that the interpreter should throw an exception if a variable is referenced before a value is assigned to the variable.

Note: A "Set-StrictMode -off" command disables the verification set by a "set-psdebug -strict" command. For more information, see Set-StrictMode.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Trace <int>

Specifies the trace level:

0 - Turn script tracing off

1 - Trace script lines as they are executed

2 - Trace script lines, variable assignments, function calls, and scripts.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not return any output.

Example 1

C:\PS>set-psdebug -trace 2; foreach ($i in 1..3) {$i}

DEBUG:    1+ Set-PsDebug -trace 2; foreach ($i in 1..3) {$i}
DEBUG:    1+ Set-PsDebug -trace 2; foreach ($i in 1..3) {$i}
1
DEBUG:    1+ Set-PsDebug -trace 2; foreach ($i in 1..3) {$i}
2
DEBUG:    1+ Set-PsDebug -trace 2; foreach ($i in 1..3) {$i}
3

Description
-----------
This command sets the trace level to 2, and then runs a script that displays the numbers 1, 2, and 3.

Example 2

C:\PS>set-psdebug -step; foreach ($i in 1..3) {$i}

DEBUG:    1+ Set-PsDebug -step; foreach ($i in 1..3) {$i}
Continue with this operation?
   1+ Set-PsDebug -step; foreach ($i in 1..3) {$i}
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):a
DEBUG:    1+ Set-PsDebug -step; foreach ($i in 1..3) {$i}
1
2
3

Description
-----------
This command turns on stepping and then
runs a script that displays the numbers 1, 2, and 3.

Example 3

C:\PS>set-psdebug -off; foreach ($i in 1..3) {$i}

1
2
3

Description
-----------
This command turns off all debugging features, and then runs a script that displays the numbers 1, 2, and 3.

Example 4

C:\PS>set-psdebug -strict; $NewVar

The variable $NewVar cannot be retrieved because it has not been set yet.
At line:1 char:28
+ Set-PsDebug -strict;$NewVar <<<<

Description
-----------
This command puts the interpreter in strict mode, and attempts to access a variable that has not yet been set.

See Also

  • about_Debuggers
  • Debug-Process
  • Set-PSBreakpoint
  • Set-StrictMode
  • Write-Debug


Set-PSSessionConfiguration

Changes the properties of a registered session configuration.

Syntax

Set-PSSessionConfiguration [-AssemblyName] <string> [-ConfigurationTypeName] <string> [-Name] <string> [-ApplicationBase <string>] [-Force] [-MaximumReceivedDataSizePerCommandMB <double>] [-MaximumReceivedObjectSizeMB <double>] [-NoServiceRestart] [-SecurityDescriptorSDDL <string>] [-ShowSecurityDescriptorUI] [-StartupScript <string>] [-ThreadApartmentState {<STA> | <MTA> | <Unknown>}] [-ThreadOptions {<Default> | <UseNewThread> | <ReuseThread> | <UseCurrentThread>}] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Set-PSSessionConfiguration cmdlet changes the properties of the registered session configurations on the local computer. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users.

Use the Name parameter to identify the configuration that you want to change. Use the other parameters to specify new values for the properties of the session configuration. To delete a property value from the configuration (and use the default value), enter an empty string ("") or a value of $null for the corresponding parameter.

To see the properties of a session configuration, use the Get-PSSessionConfiguration cmdlet or the WS-Management Provider. For more information about the WS-Management Provider, type "Get-Help wsman".

Parameters

-ApplicationBase <string>

Changes the path to the assembly file (*.dll) that is specified in the value of the AssemblyName parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AssemblyName <string>

Specifies a different assembly file for the configuration. Enter the path (optional) and file name of an assembly (.dll) file that defines the configuration type.

If you enter only the name, you can enter the path in the value of the ApplicationBase parameter.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ConfigurationTypeName <string>

Specifies a different configuration type for the configuration. The type that you specify must implement the System.Management.Automation.Remoting.PSSessionConfiguration class.

If you enter "$null" or an empty string, the DefaultRemotePowerShellConfiguration class is used for the session configuration.

Required? | true
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Suppresses all user prompts, and restarts the WinRM service without prompting. Restarting the service makes the configuration change effective.

To prevent a restart and suppress the restart prompt, use the NoServiceRestart parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MaximumReceivedDataSizePerCommandMB <double>

Changes the limit on the amount of data that can be sent to this computer in any single remote command. Enter the data size in megabytes (MB). The default is 50 MB.

If a data size limit is defined in the configuration type that is specified in the ConfigurationTypeName parameter, the limit in the configuration type is used and the value of this parameter is ignored.

Required? | false
Position? | named
Default Value | 50
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-MaximumReceivedObjectSizeMB <double>

Changes the limits on the amount of data that can be sent to this computer in any single object. Enter the data size in megabytes (MB). The default is 10 MB.

If an object size limit is defined in the configuration type that is specified in the ConfigurationTypeName parameter, the limit in the configuration type is used and the value of this parameter is ignored.

Required? | false
Position? | named
Default Value | 10
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies the name of the session configuration that you want to change.

You cannot use this parameter to change the name of the session configuration.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoServiceRestart

Does not restart the WinRM service, and suppresses the prompt to restart the service.

By default, when you enter a Set-PSSessionConfiguration command, you are prompted to restart the WinRM service to make the new session configuration effective. Until the WinRM service is restarted, the new session configuration is not effective.

To restart the WinRM service without prompting, use the Force parameter. To restart the WinRM service manually, use the Restart-Service cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SecurityDescriptorSDDL <string>

Specifies a different Security Descriptor Definition Language (SDDL) string for the configuration.

This string determines the permissions that are required to use the new session configuration. To use a session configuration in a session, users must have at least "Execute(Invoke)" permission for the configuration.

To use the default security descriptor for the configuration, enter an empty string ("") or a value of $null. The default is the root SDDL in the WSMan: drive.

If the security descriptor is complex, consider using the ShowSecurityDescriptorUI parameter instead of this one. You cannot use both parameters in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ShowSecurityDescriptorUI

Displays a property sheet that helps you to create a new SDDL for the session configuration. The property sheet appears after you enter the Set-PSSessionConfiguration command and then restart the WinRM service.

When setting the permissions to the configuration, remember that users must have at least "Execute(Invoke)" permission to use the session configuration in a session.

You cannot use the SecurityDescriptorSDDL parameter and this parameter in the same command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-StartupScript <string>

Adds or changes the startup script for the configuration. Enter the fully qualified path to a Windows PowerShell script. The specified script runs in the new session that uses the session configuration.

To delete a startup script from a session configuration, enter an empty string ("") or a value of $null.

You can use a startup script to further configure the user's session. If the script generates an error (even a non-terminating error), the session is not created and the user's New-PSSession command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThreadApartmentState <ApartmentState>

Changes the apartment state setting for the threads in the session. Valid values are STA, MTA and Unknown. Unknown is the default.

Required? | false
Position? | named
Default Value | ApartmentState.Unknown
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThreadOptions <PSThreadOptions>

Changes the thread options setting in the configuration. This setting defines how threads are created and used when a command is executed in the session. Valid values are Default, ReuseThread, UseCurrentThread, and UseNewThread. UseCurrentThread is the default.

Required? | false
Position? | named
Default Value | PSThreadOptions.UserCurrentThread
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | Microsoft.WSMan.Management.WSManConfigLeafElement

Notes

To run this cmdlet on Windows Vista, Windows Server 2008, and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option.

The Set-PSSessionConfiguration cmdlet does not change the configuration name and the WS-Management Provider does not support the Rename-Item cmdlet. To change the name of a configuration, use the Unregister-PSSessionConfiguration cmdlet to delete the configuration and then use the Register-PSSessionConfiguration cmdlet to create and register a new session configuration.

You can use the Set-PSSessionConfiguration cmdlet to change the default Microsoft.PowerShell and Microsoft.PowerShell32 session configurations. They are not protected. To revert to the original version of a default session configuration, use the Unregister-PSSessionConfiguration cmdlet to delete the default session configuration and then use the Enable-PSRemoting cmdlet to restore it.

Example 1

C:\PS>set-pssessionconfiguration -name MaintenanceShell -threadApartmentState STA

This command changes the thread apartment state in the MaintenanceShell configuration to STA. The change is effective when you restart the WinRM service.

Example 2

C:\PS>register-pssessionconfiguration -name AdminShell -assemblyName c:\shells\AdminShell.dll -configurationType AdminClass

C:\PS> set-pssessionconfiguration -name AdminShell -startupScript AdminConfig.ps1

C:\PS> set-pssessionconfiguration -name AdminShell -startupScript $null

This example shows how to create and then change a session configuration.

The first command uses the Register-PSSessionConfiguration cmdlet to create the AdminShell configuration.

The second command uses the Set-PSSessionConfiguration cmdlet to add the AdminConfig.ps1 script to the configuration. The change is effective when you restart WinRM.

The third command removes the AdminConfig.ps1 script from the configuration. It uses the Set-PSSessionConfiguration cmdlet with a value of $null for the StartupScript parameter.

Example 3

C:\PS>Set-PSSessionConfiguration -name foo -MaximumReceivedObjectSizeMB 20

WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin\foo\InitializationParameters

ParamName                       ParamValue
---------                       ----------
psmaximumreceivedobjectsizemb   20

"Restart WinRM service"
WinRM service need to be restarted to make the changes effective. Do you want to run the command "restart-service winrm"?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): y

Description
-----------
This example show sample output from the Set-PSSessionConfiguration cmdlet.

The Set-PSSessionConfiguration command in this example increases the value of the MaximumReceivedObjectSizeMB property to 20.

The Set-PSSessionConfiguration command returns a Microsoft.WSMan.Management.WSManConfigLeafElement object that shows the parameter name and new value.

It also prompts you to restart the WinRM service. The Set-PSSessionConfiguration change is not effective until the WinRM service is restarted.

Example 4

C:\PS>set-pssessionconfiguration -name MaintenanceShell -startupScript c:\ps-test\Maintenance.ps1

WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin\MaintenanceShell\InitializationParameters

ParamName            ParamValue
---------            ----------
startupscript        c:\ps-test\Mainte...

"Restart WinRM service"
WinRM service need to be restarted to make the changes effective. Do you want to run the command "restart-service winrm"?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): y

C:\PS> get-pssessionConfiguration maintenanceshell | format-list -property *

xmlns            : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration
Name             : MaintenanceShell
Filename         : %windir%\system32\pwrshplugin.dll
SDKVersion       : 1
XmlRenderingType : text
lang             : en-US
PSVersion        : 2.0
startupscript    : c:\ps-test\Maintenance.ps1
ResourceUri      : http://schemas.microsoft.com/powershell/MaintenanceShell
SupportsOptions  : true
ExactMatch       : true
Capability       : {Shell}
Permission       :

C:\PS> dir wsman:\localhost\plugin\MaintenanceShell\InitializationParameters

ParamName     ParamValue
---------     ----------
PSVersion     2.0
startupscript c:\ps-test\Maintenance.ps1

Description
-----------
This command shows different ways of viewing the results of a Set-PSSessionConfiguration command.

The first command uses the Set-PSSessionConfiguration cmdlet to change the startup script in the MaintenanceShell configuration to Maintenance.ps1. The output of this command shows the change and prompts you to restart the WinRM service. The response is "y" (yes).

The second command uses the Get-PSSessionConfiguration cmdlet to get the MaintenanceShell session configuration. The command uses a pipeline operator (|) to send the results of the command to the Format-List cmdlet, which displays all of the properties of the session configuration object in a list.

The third command uses the WS-Management provider to view the initialization parameters for the MaintenanceShell configuration. The command uses the Get-ChildItem cmdlet (alias = dir) to get the child items in the InitializationParameters node for the MaintenanceShell plug-in.

For more information about the WS-Management provider, type "get-help wsman".

See Also

  • about_Session_Configurations
  • Disable-PSSessionConfiguration
  • Enable-PSSessionConfiguration
  • Get-PSSessionConfiguration
  • Register-PSSessionConfiguration
  • Unregister-PSSessionConfiguration
  • WS-Management Provider


Set-Service

Starts, stops, and suspends a service, and changes its properties.

Syntax

Set-Service [-Name] <string> [-Description <string>] [-DisplayName <string>] [-PassThru] [-StartupType {<Automatic> | <Manual> | <Disabled>}] [-Status <string>] [-ComputerName <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Set-Service [-Description <string>] [-DisplayName <string>] [-InputObject <ServiceController>] [-PassThru] [-StartupType {<Automatic> | <Manual> | <Disabled>}] [-Status <string>] [-ComputerName <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Set-Service cmdlet changes the properties of a local or remote service, including the status, description, display name, and start mode. You can use this cmdlet to start, stop, or suspend (pause) a service. To identify the service, enter its service name or submit a service object, or pipe a service name or service object to Set-Service.

Parameters

-ComputerName <string[]>

Specifies one or more computers. The default is the local computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Set-Service even if your computer is not configured to run remote commands.

Required? | false
Position? | named
Default Value | local computer
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Description <string>

Specifies a new description for the service.

The service description appears in Services in Computer Management. Description is not a property of the ServiceController object that Get-Service gets. To see the service description, use Get-WmiObject to get a Win32_Service object that represents the service.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-DisplayName <string>

Specifies a new display name for the service.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ServiceController>

Specifies a ServiceController object that represents the service to be changed. Enter a variable that contains the object, or type a command or expression that gets the object, such as a Get-Service command. You can also pipe a service object to Set-Service.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string>

Specifies the service name of the service to be changed. Wildcards are not permitted. You can also pipe a service name to Set-Service.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns objects that represent the services that were changed. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-StartupType <ServiceStartMode>

Changes the start mode of the service. Valid values for StartupType are:

-- Automatic: Start when the system starts.

-- Manual: Starts only when started by a user or program.

-- Disabled: Cannot be started.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Status <string>

Starts, stops, or suspends (pauses) the services. Valid values are:

-- Running: Starts the service.

-- Stopped: Stops the service.

-- Paused: Suspends the service.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.ServiceProcess.ServiceController, System.String You can pipe a service object or a string that contains a service name to Set-Service.
Outputs | None This cmdlet does not return any objects.

Notes

To use Set-Service on Windows Vista and later versions of Windows, start Windows PowerShell with the "Run as administrator" option.

Set-Service can control services only when the current user has permission to do so. If a command does not work correctly, you might not have the required permissions.

To find the service names and display names of the services on your system, type "Get-Service". The service names appear in the Name column and the display names appear in the DisplayName column.

Example 1

C:\PS>set-service -name lanmanworkstation -DisplayName "LanMan Workstation"

This command changes the display name of the lanmanworkstation service to "LanMan Workstation". (The default is "Workstation".)

Example 2

C:\PS>get-wmiobject win32_service -filter "name = 'SysmonLog'"

ExitCode  : 0
Name      : SysmonLog
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

C:\PS> set-service sysmonlog -startuptype automatic

C:\PS> get-wmiobject win32_service -filter "name = 'SysmonLog'"

ExitCode  : 0
Name      : SysmonLog
ProcessId : 0
StartMode : Auto
State     : Stopped
Status    : OK

C:\PS> get-wmiobject win32_service | format-table Name, StartMode -auto

Name                                  StartMode
----                                  ---------
AdtAgent                              Auto
Alerter                               Disabled
ALG                                   Manual
AppMgmt                               Manual
...

Description
-----------
These commands get the startup type of the Performance Logs and Alerts (SysmonLog) service, set the start mode to automatic, and then display the result of the change.

These commands use the Get-WmiObject cmdlet to get the Win32_Service object for the service, because the ServiceController object that Get-Service returns does not include the start mode.

The first command uses the Get-WmiObject cmdlet to get the Windows Management Instrumentation (WMI) object that represents the SysmonLog service. The default output of this command displays the start mode of the service.

The second command uses Set-Service to change the start mode to automatic. Then, the first command is repeated to display the change.

The final command displays the start mode of all services on the computer.

Example 3

C:\PS>set-service -name Schedule -computername S1 -description "Configures and schedules tasks."

C:\PS> get-wmiobject win32_service -computername s1 | where-object {$_.Name -eq "Schedule"} | format-list Name, Description

These commands change the description of the Task Scheduler service on the S1 remote computer and then display the result.

These commands use the Get-WmiObject cmdlet to get the Win32_Service object for the service, because the ServiceController object that Get-Service returns does not include the service description.

The first command  uses a Set-Service command to change the description. It identifies the service by using the service name of the service, "Schedule".

The second command uses the Get-WmiObject cmdlet to get an instance of the WMI Win32_Service that represents the Task Scheduler service. The first element in the command gets all instances of the Win32_service class.

The pipeline operator (|) passes the result to the Where-Object cmdlet, which selects instances with a value of "Schedule" in the Name property.

Another pipeline operator sends the result to the Format-List cmdlet, which formats the output as a list with only the Name and Description properties.

Example 4

C:\PS>set-service winrm -status Running -passthru -computername Server02

This command starts the WinRM service on the Server02 computer. The command uses the Status parameter to specify the desired status ("running") and the PassThru parameter to direct Set-Service to return an object that represents the WinRM service.

Example 5

C:\PS>get-service schedule -computername S1, S2 | set-service -status paused

This command suspends the Schedule service on the S1 and S2 remote computers. It uses the Get-Service cmdlet to get the service. A pipeline operator (|) sends the service to the Set-Service cmdlet, which changes its status to "Paused".

Example 6

C:\PS>$s = get-service schedule

C:\PS> set-service -inputobject $s -status stopped

These commands stop the Schedule service on the local computer.

The first command uses the Get-Service cmdlet to get the Schedule service. The command saves the service in the $s variable.

The second command uses the Set-Service cmdlet to change the status of the Schedule service to "Stopped". It uses the InputObject parameter to submit the service stored in the $s variable, and it uses the Status parameter to specify the desired status.

See Also

  • Get-Service
  • Start-Service
  • Stop-Service
  • Restart-Service
  • Resume-Service
  • Suspend-Service
  • New-Service


Set-StrictMode

Establishes and enforces coding rules in expressions, scripts, and script blocks.

Syntax

Set-StrictMode -Off [<CommonParameters>]

Set-StrictMode -Version <Version> [<CommonParameters>]

Description

The Set-StrictMode cmdlet configures strict mode for the current scope (and all child scopes) and turns it on and off. When strict mode is on, Windows PowerShell generates a terminating error when the content of an expression, script, or script block violates basic best-practice coding rules.

Use the Version parameter to determine which coding rules are enforced.

Unlike the Set-PSDebug cmdlet, Set-StrictMode affects only the current scope and its child scopes, so you can use it in a script or function without affecting the global scope.

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $null, depending on type. References to non-existent properties return $null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

Parameters

-Off

Turns strict mode off. This parameter also turns off "Set-PSDebug -Strict".

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Version <Version>

Specifies the conditions that cause an error in strict mode. This parameter is required.

The valid values are "1.0", "2.0", and "Latest". The following list shows the effect of each value.

1.0

-- Prohibits references to uninitialized variables, except for uninitialized variables in strings.

2.0

-- Prohibits references to uninitialized variables (including uninitialized variables in strings).

-- Prohibits references to non-existent properties of an object.

-- Prohibits function calls that use the syntax for calling methods.

-- Prohibits a variable without a name (${}).

Latest:

--Selects the latest (most strict) version available. Use this value to assure that scripts use the strictest available version, even when new versions are added to Windows PowerShell.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not return any output.

Notes

Set-StrictMode is similar to the Strict parameter of Set-PSDebug. "Set-Strictmode -version 1" is equivalent to "Set-PSDebug -strict", except that Set-PSDebug is effective in all scopes. Set-StrictMode is effective only in the scope in which it is set and in its child scopes. For more information about scopes in Windows PowerShell, see about_Scopes.

Example 1

C:\PS>set-strictmode -version 1.0

C:\PS> $a -gt 5
False
The variable $a cannot be retrieved because it has not been set yet.
At line:1 char:3
+ $a <<<<  -gt 5
    + CategoryInfo          : InvalidOperation: (a:Token) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

Description
-----------
This command turns strict mode on and sets it to version 1.0. As a result, attempts to reference variables that are not initialized will fail.

The sample output shows the effect of version 1.0 strict mode.

Example 2

C:\PS># set-strictmode -version 2.0

# Strict mode is off by default.

C:\PS> function add ($a, $b) {$a + $b}
C:\PS> add 3 4
7
C:\PS> add(3,4)
3
4

C:\PS> set-strictmode -version 2.0

C:\PS> add(3,4)

The function or command was called like a method. Parameters should be separated by spaces, as described in 'Get-Help about_Parameter.'
At line:1 char:4
+ add <<<< (3,4)
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : StrictModeFunctionCallWithParens

C:\PS> set-strictmode -off

C:\PS> $string = "This is a string".
C:\PS> $string.Month
C:\PS>

C:\PS> set-strictmode -version 2.0

C:\PS> $string = "This is a string".
C:\PS> $string.Month
Property 'month' cannot be found on this object; make sure it exists.
At line:1 char:9
+ $string. <<<< month
    + CategoryInfo          : InvalidOperation: (.:OperatorToken) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

Description
-----------
This command turns strict mode on and sets it to version 2.0. As a result, Windows PowerShell throws an error if you use method syntax (parentheses and commas) for a function call or reference uninitialized variables or non-existent properties.

The sample output shows the effect of version 2.0 strict mode.

Without version 2.0 strict mode, the "(3,4)" value is interpreted as a single array object to which nothing is added. With version 2.0 strict mode, it is correctly interpreted as faulty syntax for submitting two values.

Without version 2.0, the reference to the non-existent Month property of a string returns only null. With version 2.0, it is interpreted correctly as a reference error.

See Also

  • about_Debuggers
  • about_Scopes
  • Set-PSDebug


Set-TraceSource

Configures, starts, and stops a trace of Windows PowerShell components.

Syntax

Set-TraceSource [[-Option] {<None> | <Constructor> | <Dispose> | <Finalizer> | <Method> | <Property> | <Delegates> | <Events> | <Exception> | <Lock> | <Error> | <Errors> | <Warning> | <Verbose> | <WriteLine> | <Data> | <Scope> | <ExecutionFlow> | <Assert> | <All>}] [-Debugger] [-FilePath <string>] [-Force] [-ListenerOption {<None> | <LogicalOperationStack> | <DateTime> | <Timestamp> | <ProcessId> | <ThreadId> | <Callstack>}] [-PassThru] [-PSHost] [-Name] <string[]> [<CommonParameters>]

Set-TraceSource [-RemoveListener <string[]>] [-Name] <string[]> [<CommonParameters>]

Set-TraceSource [-RemoveFileListener <string[]>] [-Name] <string[]> [<CommonParameters>]

Description

The Set-TraceSource cmdlet configures, starts, and stops a trace of a Windows PowerShell component. You can use it to specify which components will be traced and where the tracing output is sent.

Parameters

-Debugger

Sends the trace output to the debugger. You can view the output in any user-mode or kernel mode debugger or in Microsoft Visual Studio. This parameter also selects the default trace listener.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilePath <string>

Sends the trace output to the specified file. This parameter also selects the file trace listener. If you use this parameter to start the trace, use the RemoveFileListener parameter to stop the trace.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to overwrite a read-only file. Use with the FilePath parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ListenerOption <TraceOptions>

Adds optional data to the prefix of each trace message in the output. The valid values are "None", "LogicalOperationStack", "DateTime", "Timestamp", "ProcessId", "ThreadId", and "Callstack". "None" is the default.

To specify multiple options, separate them with commas, but with no spaces, and enclose them in quotation marks, such as "ProcessID,ThreadID".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Determines which components are traced. Enter the name of the trace source of each component. Wildcards are permitted.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Option <PSTraceSourceOptions>

Determines the type of events that are traced.

The valid values are: "None", "Constructor", "Dispose", "Finalizer", "Method", "Property", "Delegates", "Events", "Exception", "Lock", "Error", "Errors", "Warning", "Verbose", "WriteLine", "Data", "Scope", "ExecutionFlow", "Assert", and "All". "All" is the default.

The following values are combinations of other values:

-- ExecutionFlow: (Constructor, Dispose, Finalizer, Method, Delegates, Events, and Scope)

-- Data: (Constructor, Dispose, Finalizer, Property, Verbose, and WriteLine)

-- Errors: (Error and Exception).

To specify multiple options, separate them with commas, but with no spaces, and enclose them in quotation marks, such as "Constructor,Dispose".

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the trace session. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PSHost

Sends the trace output to the Windows PowerShell host. This parameter also selects the PSHost trace listener.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RemoveFileListener <string[]>

Stops the trace by removing the file trace listener associated with the specified file. Enter the path and file name of the trace output file.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RemoveListener <string[]>

Stops the trace by removing the trace listener.

Use the following values with RemoveListener:

--To remove PSHost (console), type "Host".

--To remove Debugger, type "Debug".

--To remove all trace listeners, type "*".

To remove the file trace listener, use the RemoveFileListener parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a name to Set-TraceSource.
Outputs | None or System.Management.Automation.PSTraceSource When you use the PassThru parameter, Set-TraceSource generates a System.Management.Automation.PSTraceSource object representing the trace session. Otherwise, this cmdlet does not generate any output.

Notes

Tracing is a method that developers use to debug and refine programs. When tracing, the program generates detailed messages about each step in its internal processing.

The Windows PowerShell tracing cmdlets are designed to help Windows PowerShell developers, but they are available to all users. They let you monitor nearly every aspect of the functionality of Windows PowerShell.

A "trace source" is the part of each Windows PowerShell component that manages tracing and generates trace messages for the component. To trace a component, you identify its trace source.

A "trace listener" receives the output of the trace and displays it to the user. You can elect to send the trace data to a user-mode or kernel-mode debugger, to the console, to a file, or to a custom listener derived from the System.Diagnostics.TraceListener class.

To start a trace, use the Name parameter to specify a trace source (the component to be traced) and the FilePath, Debugger, or PSHost parameters to specify a listener (a destination for the output). Use the Options parameter to determine the types of events that are traced and the ListenerOptions parameter to configure the trace output.

To change the configuration of a trace, enter a Set-TraceSource command as you would to start a trace. Windows PowerShell recognizes that the trace source is already being traced. It stops the trace, adds the new configuration, and starts or restarts the trace.

To stop a trace, use the RemoveListener parameter. To stop a trace that uses the file listener (a trace started by using the -FilePath parameter), use the RemoveFileListener parameter. When you remove the listener, the trace stops.

To determine which components can be traced, use Get-TraceSource. The trace sources for each module are loaded automatically when the component is in use, and they appear in the output of Get-TraceSource.

Example 1

C:\PS>Set-TraceSource -Name Parameterbinding -Option ExecutionFlow -PSHost '
-ListenerOption "ProcessID,TimeStamp"

This command starts tracing for the ParameterBinding component of Windows PowerShell. It uses the Name parameter to specify the trace source, the Option parameter to select the ExecutionFlow trace events, and the PSHost parameter to select the Windows PowerShell host listener, which sends the output to the console. The ListenerOption parameter adds the "ProcessID" and "TimeStamp" values to the trace message prefix.

Example 2

C:\PS>set-tracesource -name ParameterBinding -RemoveListener Host

This command stops the trace of the ParameterBinding component of Windows PowerShell. It uses the Name parameter to identify the component that was being traced and the RemoveListener parameter to identify the trace listener.

See Also

  • Get-TraceSource
  • Trace-Command
  • Set-PSDebug


Set-Variable

Sets the value of a variable. Creates the variable if one with the requested name does not exist.

Syntax

Set-Variable [-Name] <string[]> [[-Value] <Object>] [-Description <string>] [-Exclude <string[]>] [-Force] [-Include <string[]>] [-Option {<None> | <ReadOnly> | <Constant> | <Private> | <AllScope>}] [-PassThru] [-Scope <string>] [-Visibility {<Public> | <Private>}] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Set-Variable cmdlet assigns a value to a specified variable or changes the current value. If the variable does not exist, the cmdlet creates it.

Parameters

-Description <string>

Specifies the description of the variable.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows you to create a variable with the same name as an existing read-only variable, or to change the value of a read-only variable.

By default, you can overwrite a variable, unless the variable has an option value of "ReadOnly" or "Constant". For more information, see the Option parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Changes only the specified items. The value of this parameter qualifies the Name parameter. Enter a name or name pattern, such as "c*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the variable name.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Option <ScopedItemOptions>

Changes the value of the Options property of the variable. Valid values are:

-- None: Sets no options. ("None" is the default.)

-- ReadOnly: The properties of the variable cannot be changed, except by using the Force parameter. You can use Remove-Variable to delete the variable.

-- Constant: The variable cannot be deleted and its properties cannot be changed. "Constant" is available only when you are creating an alias. You cannot change the option of an existing variable to "Constant".

-- Private: The variable is available only within the scope specified by the Scope parameter. It is inherited by child scopes.

-- AllScope: The variable is copied to any new scopes that are created.

To see the Options property of the variables, type "get-variable| Format-Table -property name, options -autosize".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the new variable. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Scope <string>

Determines the scope of the variable. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Value <Object>

Specifies the value of the variable.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Visibility <SessionStateEntryVisibility>

Determines whether the variable is visible outside of the session in which it was created. This parameter is designed for use in scripts and commands that will be delivered to other users.

Valid values are:

-- Public: The variable is visible. ("Public" is the default.)

-- Private: The variable is not visible.

When a variable is private, it does not appear in lists of variables, such as those returned by Get-Variable, or in displays of the Variable: drive. Commands to read or change the value of a private variable return an error. However, the user can run commands that use a private variable if the commands were written in the session in which the variable was defined.

Required? | false
Position? | named
Default Value | Public
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Object You can pipe an object that represents the value of the variable to Set-Variable.
Outputs | None or System.Management.Automation.PSVariable When you use the PassThru parameter, Set-Variable generates a System.Management.Automation.PSVariable object representing the new or changed variable. Otherwise, this cmdlet does not generate any output.

Example 1

C:\PS>set-variable -name desc -value "A description"

C:\PS>get-variable -name desc

These commands set the value of the "desc" variable to "A description", and then get the value of the variable.

Example 2

C:\PS>set-variable -name processes -value (Get-Process) -option constant -scope global -description "All processes" -passthru | format-list -property *

This command creates a global, read-only variable that contains all processes on the system, and then it displays all properties of the variable.

The command uses the Set-Variable cmdlet to create the variable. It uses the PassThru parameter to create an object representing the new variable, and it uses the pipeline operator (|) to pass the object to the Format-List cmdlet. It uses the Property parameter of Format-List with a value of all (*) to display all properties of the newly created variable.

The value, "(Get-Process)", is enclosed in parentheses to ensure that it is executed before being stored in the variable. Otherwise, the variable contains the words "Get-Process".

Example 3

C:\PS># set-variable -name counter -visibility private

C:\PS> new-variable -name counter -visibility public -value 26

C:\PS> $counter
26

C:\PS> get-variable c*

Name Value
---- -----
Culture en-US
ConsoleFileName
ConfirmPreference High
CommandLineParameters {}
Counter 26

C:\PS> set-variable -name counter -visibility private

C:\PS> get-variable c*

Name Value
---- -----
Culture en-US
ConsoleFileName
ConfirmPreference High
CommandLineParameters {}

C:\PS> $counter
"Cannot access the variable '$counter' because it is a private variable"

C:\PS> .\use-counter.ps1
Commands completed successfully.

Description
-----------
This command shows how to change the visibility of a variable to "Private". This variable can be read and changed by scripts with the required permissions, but it is not visible to the user.

The sample output shows the difference in the behavior of public and private variables.

See Also

  • Get-Variable
  • New-Variable
  • Remove-Variable
  • Clear-Variable


Set-WmiInstance

Creates or updates an instance of an existing Windows Management Instrumentation (WMI) class.

Syntax

Set-WmiInstance [-Class] <string> [[-Arguments] <hashtable>] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {<None> | <UpdateOnly> | <CreateOnly> | <UpdateOrCreate>}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Set-WmiInstance [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {<None> | <UpdateOnly> | <CreateOnly> | <UpdateOrCreate>}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Set-WmiInstance -InputObject <ManagementObject> [-Arguments <hashtable>] [-AsJob] [-PutType {<None> | <UpdateOnly> | <CreateOnly> | <UpdateOrCreate>}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Set-WmiInstance -Path <string> [-Arguments <hashtable>] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {<None> | <UpdateOnly> | <CreateOnly> | <UpdateOrCreate>}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Set-WmiInstance [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {<None> | <UpdateOnly> | <CreateOnly> | <UpdateOrCreate>}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Set-WmiInstance [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {<None> | <UpdateOnly> | <CreateOnly> | <UpdateOrCreate>}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Set-WmiInstance cmdlet creates or updates an instance of an existing WMI class. The created or updated instance is written to the WMI repository.

Parameters

-Arguments <hashtable>

Specifies the name of the property to be changed and the new value for that property. The name and value must be in a name-value pair. The name-value pair is passed on the command-line as a hash table. For example:

-argument @{Setting1=1; Setting2=5; Setting3="test"}.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-AsJob

Runs the command as a background job. Use this parameter to run commands that take a long time to finish.

When you use the AsJob parameter, the command returns an object that represents the background job and then displays the command prompt. You can continue to work in the session while the job finishes. If Set-WmiObject is used against a remote computer, the job is created on the local computer, and the results from remote computers are automatically returned to the local computer. To manage the job, use the cmdlets that contain the Job noun (the Job cmdlets). To get the job results, use the Receive-Job cmdlet.

Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must start Windows PowerShell by using the "Run as administrator" option in Windows Vista and later versions of Windows,. For more information, see about_Remote_Requirements.

For more information about Windows PowerShell background jobs, see about_Jobs and about_Remote_Jobs.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationLevel>

Specifies the authentication level to be used with the WMI connection. Valid values are:

-1: Unchanged

0: Default

1: None (No authentication in performed.)

2: Connect (Authentication is performed only when the client establishes a relationship with the application.)

3: Call (Authentication is performed only at the beginning of each call when the application receives the request.)

4: Packet (Authentication is performed on all the data that is received from the client.)

5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.)

6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.)

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authority <string>

Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to ntlmdomain:<DomainName>, where <DomainName> identifies a valid NTLM domain name. To use Kerberos, specify kerberos:<DomainName>\<ServerName>". You cannot include the authority setting when you connect to the local computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Class <string>

Specifies the name of a WMI class.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name. You can set the value of this parameter by piping the value to the parameter.

This parameter does not rely on Windows PowerShell remoting, which uses WS-Management ). You can use the ComputerName parameter of Get-WmiObject even if your computer is not configured to run WS-Management remote commands.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or User@Contoso.com. Or, enter a PSCredential object, such as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-EnableAllPrivileges

Enables all the privileges of the current user before the command makes the WMI call .

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Impersonation <ImpersonationLevel>

Specifies the impersonation level to use. Valid values are:

0: Default (Reads the local registry for the default impersonation level, which is usually set to "3: Impersonate".)

1: Anonymous (Hides the credentials of the caller.)

2: Identify (Allows objects to query the credentials of the caller.)

3: Impersonate (Allows objects to use the credentials of the caller.)

4: Delegate (Allows objects to permit other objects to use the credentials of the caller.)

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ManagementObject>

Specifies a ManagementObject object to use as input. When this parameter is used, all other parameters ,except the Arguments parameter, are ignored.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Locale <string>

Specifies the preferred locale for WMI objects. The Locale parameter is specified in an array in the MS_<LCID> format in the preferred order.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Namespace <string>

When used with the Class parameter, this parameter specifies the WMI repository namespace where the referenced WMI class is located.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies a WMI object path to the instance that you want to create or update.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PutType <PutType>

Indicates whether the WMI instance should be created or updated. Valid values are:

UpdateOnly: Updates an existing WMI instance.

CreateOnly: Creates a new WMI instance.

UpdateOrCreate: Updates the WMI instance if it exists or creates a new instance if an instance does not exist.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Allows the user to specify a throttling value for the number of WMI operations that can be executed simultaneously. This parameter is used together with the AsJob parameter. The throttle limit applies only to the current command, not to the session or to the computer.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept input.
Outputs | None This cmdlet does not generate output.

Example 1

C:\PS>Set-WMIInstance -class Win32_WMISetting -argument @{LoggingLevel=2}

__GENUS                        : 2
__CLASS                        : Win32_WMISetting
__SUPERCLASS                   : CIM_Setting
__DYNASTY                      : CIM_Setting
__RELPATH                      : Win32_WMISetting=@
__PROPERTY_COUNT               : 27
__DERIVATION                   : {CIM_Setting}
__SERVER                       : SYSTEM01
__NAMESPACE                    : root\cimv2
__PATH                         : \\SYSTEM01\root\cimv2:Win32_WMISetting=@
ASPScriptDefaultNamespace      : \\root\cimv2
ASPScriptEnabled               : False
AutorecoverMofs                : {%windir%\system32\wbem\cimwin32.mof, %windir%\system32\wbem\ncprov.mof, %windir%\syst
                                 em32\wbem\wmipcima.mof, %windir%\system32\wbem\secrcw32.mof...}
AutoStartWin9X                 :
BackupInterval                 :
BackupLastTime                 :
BuildVersion                   : 6001.18000
Caption                        :
DatabaseDirectory              : C:\Windows\system32\wbem\repository
DatabaseMaxSize                :
Description                    :
EnableAnonWin9xConnections     :
EnableEvents                   : False
EnableStartupHeapPreallocation : False
HighThresholdOnClientObjects   :
HighThresholdOnEvents          : 20000000
InstallationDirectory          : C:\Windows\system32\wbem
LastStartupHeapPreallocation   :
LoggingDirectory               : C:\Windows\system32\wbem\Logs\
LoggingLevel                   : 2
LowThresholdOnClientObjects    :
LowThresholdOnEvents           : 10000000
MaxLogFileSize                 : 65536
MaxWaitOnClientObjects         :
MaxWaitOnEvents                : 2000
MofSelfInstallDirectory        :
SettingID                      :

Description
-----------
This command sets the WMI logging level to 2. The command passes the property to be set and the value (together considered a value pair) in the argument parameter. The parameter takes a hash table that is defined by the @{property = value} construction. Theclass information that is returned reflects the new value.

Example 2

C:\PS>set-wmiinstance -class win32_environment -argument @{Name="testvar";VariableValue="testvalue";UserName="<SYSTEM>"}

__GENUS          : 2
__CLASS          : Win32_Environment
__SUPERCLASS     : CIM_SystemResource
__DYNASTY        : CIM_ManagedSystemElement
__RELPATH        : Win32_Environment.Name="testvar",UserName="<SYSTEM>"
__PROPERTY_COUNT : 8
__DERIVATION     : {CIM_SystemResource, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER         : SYSTEM01
__NAMESPACE      : root\cimv2
__PATH           : \\SYSTEM01\root\cimv2:Win32_Environment.Name="testvar",UserName="<SYSTEM>"
Caption          : <SYSTEM>\testvar
Description      : <SYSTEM>\testvar
InstallDate      :
Name             : testvar
Status           : OK
SystemVariable   : True
UserName         : <SYSTEM>
VariableValue    : testvalue

Description
-----------
This command creates the testvar environment variable that has  the value "testvalue". It does this by creating a new instance of the Win32_Environment WMI class. Note that this operation requires appropriate credentials and that you may need to restart Windows PowerShell to see the new environment variable.

Example 3

C:\PS>Set-WMIInstance -class Win32_WMISetting -argument @{LoggingLevel=2} -computername system01, system02, system03

__GENUS                        : 2
__CLASS                        : Win32_WMISetting
__SUPERCLASS                   : CIM_Setting
__DYNASTY                      : CIM_Setting
__RELPATH                      : Win32_WMISetting=@
__PROPERTY_COUNT               : 27
__DERIVATION                   : {CIM_Setting}
__SERVER                       : SYSTEM01
__NAMESPACE                    : root\cimv2
__PATH                         : \\SYSTEM01\root\cimv2:Win32_WMISetting=@
ASPScriptDefaultNamespace      : \\root\cimv2
ASPScriptEnabled               : False
AutorecoverMofs                : {%windir%\system32\wbem\cimwin32.mof, %windir%\system32\wbem\ncprov.mof, %windir%\syst
                                 em32\wbem\wmipcima.mof, %windir%\system32\wbem\secrcw32.mof...}
AutoStartWin9X                 :
BackupInterval                 :
BackupLastTime                 :
BuildVersion                   : 6001.18000
Caption                        :
DatabaseDirectory              : C:\Windows\system32\wbem\repository
DatabaseMaxSize                :
Description                    :
EnableAnonWin9xConnections     :
EnableEvents                   : False
EnableStartupHeapPreallocation : False
HighThresholdOnClientObjects   :
HighThresholdOnEvents          : 20000000
InstallationDirectory          : C:\Windows\system32\wbem
LastStartupHeapPreallocation   :
LoggingDirectory               : C:\Windows\system32\wbem\Logs\
LoggingLevel                   : 2
LowThresholdOnClientObjects    :
LowThresholdOnEvents           : 10000000
MaxLogFileSize                 : 65536
MaxWaitOnClientObjects         :
MaxWaitOnEvents                : 2000
MofSelfInstallDirectory        :
SettingID                      :

...

Description
-----------
This command sets the WMI logging level to 2. The command passes the property to be set and the value (together considered a value pair) in the argument parameter. The parameter takes a hash table that is defined by the @{property = value} construction. The returned class information reflects the new value.

See Also

  • Get-WmiObject
  • Invoke-WmiMethod
  • Remove-WmiObject
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • Remove-WSManInstance


Set-WSManInstance

Modifies the management information that is related to a resource.

Syntax

Set-WSManInstance [-ApplicationName <string>] [-ComputerName <string>] [-Fragment <string>] [-Port <int>] [-UseSSL] -ResourceURI <Uri> [[-SelectorSet] <hashtable>] [-Authentication <AuthenticationMechanism>] [-Credential <PSCredential>] [-Dialect <Uri>] [-FilePath <File>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

Set-WSManInstance [-ConnectionURI <Uri>] [-Fragment <string>] -ResourceURI <Uri> [[-SelectorSet] <hashtable>] [-Authentication <AuthenticationMechanism>] [-Credential <PSCredential>] [-Dialect <Uri>] [-FilePath <File>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

Description

The Set-WSManInstance cmdlet modifies the management information that is related to a resource.

This cmdlet uses the WinRM connection/transport layer to modify the information.

Parameters

-ApplicationName <string>

Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for the remote endpoint is in the following format:

<transport>://<server>:<port>/<ApplicationName>

For example:

http://server01:8080/WSMAN

Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management ) for efficiency.

Required? | false
Position? | named
Default Value | wsman
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationMechanism>

Specifies the authentication mechanism to be used at the server. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.

- Default : Use the authentication method implemented by the WS-Management protocol. This is the default.

- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

- Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates.

- Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.

- CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

Caution: CredSSP delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

Required? | false
Position? | named
Default Value | localhost
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ConnectionURI <Uri>

Specifies the connection endpoint. The format of this string is:

<Transport>://<Server>:<Port>/<ApplicationName>

The following string is a properly formatted value for this parameter:

http://Server01:8080/WSMAN

The URI must be fully qualified .

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Domain.com". Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Dialect <Uri>

Specifies the dialect to use in the filter predicate. This can be any dialect that is supported by the remote service. The following aliases can be used for the dialect URI:

- WQL: http://schemas.microsoft.com/wbem/wsman/1/WQL

- Selector: http://schemas.microsoft.com/wbem/wsman/1/wsman/SelectorFilter

- Association: http://schemas.dmtf.org/wbem/wsman/1/cimbinding/associationFilter

Required? | false
Position? | named
Default Value | http://schemas.microsoft.com/wbem/wsman/1/WQL
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilePath <File>

Specifies the path of a file that is used to update a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter . For example, the following command uses the FilePath parameter:

invoke-wsmanaction -action stopservice -resourceuri wmicimv2/Win32_Service -SelectorSet @{Name="spooler"} -FilePath:c:\input.xml -authentication default

This command calls the StopService method on the Spooler service by using input from a file. The file, Input.xml, contains the following content:

<p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service"/>

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Fragment <string>

Specifies a section inside the instance that is to be updated or retrieved for the specified operation. For example, to get the status of a spooler service, specify "-Fragment Status".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-OptionSet <hashtable>

Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified.

The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters:

-OptionSet @{a=1;b=2;c=3}

Required? |
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Port <int>

Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server's certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted machines.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ResourceURI <Uri>

Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer.

A URI consists of a prefix and a path to a resource. For example:

http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk

http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SelectorSet <hashtable>

Specifies a set of value pairs that are used to select particular management resource instances. The SelectorSet parameter is used when more than one instance of the resource exists. The value of the SelectorSet parameter must be a hash table. The following example shows how to enter a value for this parameter:

-SelectorSet @{Name="WinRM";ID="yyy"}

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-SessionOption <hashtable>

Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, see New-WSManSessionOption.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used.

WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ValueSet <hashtable>

Specifies a hash table that helps modify a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. The value of the ValueSet parameter must be a hash table.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>set-wsmaninstance -resourceuri winrm/config/listener -selectorset @{address="*";transport="https"} -valueset @{Enabled="false"}

cfg                   : http://schemas.microsoft.com/wbem/wsman/1/config/listener
xsi                   : http://www.w3.org/2001/XMLSchema-instance
lang                  : en-US
Address               : *
Transport             : HTTPS
Port                  : 443
Hostname              :
Enabled               : false
URLPrefix             : wsman
CertificateThumbprint :
ListeningOn           : {127.0.0.1, 172.30.168.171, ::1, 2001:4898:0:fff:0:5efe:172.30.168.171...}

Description
-----------
This command disables the https listener on the local computer.

Important: The ValueSet parameter is case-sensitive when matching the properties specified.

For example, using the above command.

This fails:     -ValueSet @{enabled="False"}

This succeeds:  -ValueSet @{Enabled="False"}

Example 2

C:\PS>set-wsmaninstance -resourceuri winrm/config -ValueSet @{MaxEnvelopeSizekb = "200"}

cfg                 : http://schemas.microsoft.com/wbem/wsman/1/config
lang                : en-US
MaxEnvelopeSizekb   : 200
MaxTimeoutms        : 60000
MaxBatchItems       : 32000
MaxProviderRequests : 4294967295
Client              : Client
Service             : Service
Winrs               : Winrs

Description
-----------
This command sets the MaxEnvelopeSizekb value to 200 on the local computer.

Important: The ValueSet parameter is case-sensitive when matching the properties specified.

For example, using the above command.

This fails:     -ValueSet @{MaxEnvelopeSizeKB ="200"}

This succeeds:  -ValueSet @{MaxEnvelopeSizekb ="200"}

Example 3

C:\PS>set-wsmaninstance -resourceuri winrm/config/listener -computername SERVER02 -selectorset @{address="*";transport="https"} -valueset @{Enabled="false"}

cfg                   : http://schemas.microsoft.com/wbem/wsman/1/config/listener
xsi                   : http://www.w3.org/2001/XMLSchema-instance
lang                  : en-US
Address               : *
Transport             : HTTPS
Port                  : 443
Hostname              :
Enabled               : false
URLPrefix             : wsman
CertificateThumbprint :
ListeningOn           : {127.0.0.1, 172.30.168.172, ::1, 2001:4898:0:fff:0:5efe:172.30.168.172...}

Description
-----------
This command disables the https listener on the remote computer SERVER02.

Important: The ValueSet parameter is case-sensitive when matching the properties specified.

For example, using the above command.

This fails:     -ValueSet @{enabled="False"}

This succeeds:  -ValueSet @{Enabled="False"}

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManQuickConfig
  • Test-WSMan


Set-WSManQuickConfig

Configures the local computer for remote management.

Syntax

Set-WSManQuickConfig [-UseSSL] [<CommonParameters>]

Description

The Set-WSManQuickConfig cmdlet configures the computer to receive Windows PowerShell remote commands that are sent by using the Web Services for Management (WS-Management) technology.

The cmdlet performs the following:

1. Checks whether the WinRM service is running. If the WinRM service is not running, the service is started.

2. Sets the WinRM service startup type to automatic.

3. Creates a listener to accept requests on any IP address. By default, the transport is HTTP.

4. Enables a firewall exception for WinRM traffic .

To run this cmdlet in Windows Vista, Windows Server 2008, and later versions of Windows, you must start Windows PowerShell with the "Run as administrator" option.

Parameters

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connnection to the remote computer. By default, SSL is not used.

WS-Management encrypts all Windows PowerShell content transmitted over the network. The UseSSL parameter lets you specify that the additional protection of using HTTPS instead of HTTP should be used. If you specify this parameter, but SSL is not available on the port used for the connection, the command fails.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>Set-WSManQuickConfig

This command sets the required configuration to enable remote management of the local computer. By default, this command creates a WS-Management listener on HTTP.

Example 2

C:\PS>Set-WSManQuickConfig -UseSSL

The command sets the required configuration to enable remote management of the local computer. The UseSSL parameter makes the command create a WS-Management listener on HTTPS.

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-PSRemoting
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-PSSession
  • New-WSManInstance
  • New-WSManSessionOption
  • Test-WSMan


Show-Eventlog

Displays the event logs of the local or a remote computer in Event Viewer.

Syntax

Show-EventLog [[-ComputerName] <string>] [<CommonParameters>]

Description

The Show-EventLog cmdlet opens Event Viewer on the local computer and displays in it all of the classic event logs on the local computer or a remote computer.

To open Event Viewer on Windows Vista and later versions of Windows, the current user must be a member of the Administrators group on the local computer.

The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.

Parameters

-ComputerName <string>

Specifies a remote computer. Show-EventLog displays the event logs from the specified computer in Event Viewer on the local computer. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name of a remote computer.

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-EventLog even if your computer is not configured to run remote commands.

Required? | false
Position? | 1
Default Value | .
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not generate any output.

Notes

The Windows PowerShell command prompt returns as soon as Event Viewer opens. You can work in the current session while Event Viewer is open.

Because this cmdlet requires a user interface, it does not work on Server Core installations of Windows Server.

Example 1

C:\PS>show-eventlog

This command opens Event Viewer and displays in it the classic event logs on the local computer.

Example 2

C:\PS>show-eventlog -computername Server01

This command opens Event Viewer and displays in it the classic event logs on the Server01 computer.

See Also

  • Clear-EventLog
  • Get-EventLog
  • Limit-EventLog
  • New-EventLog
  • Remove-EventLog
  • Write-EventLog
  • Get-WinEvent


Sort-Object

Sorts objects by property values.

Syntax

Sort-Object [[-Property] <Object[]>] [-CaseSensitive] [-Culture <string>] [-Descending] [-InputObject <psobject>] [-Unique] [<CommonParameters>]

Description

The Sort-Object cmdlet sorts objects in ascending or descending order based on the values of properties of the object.

You can specify a single property or multiple properties (for a multi-key sort), and you can select a case-sensitive or case-insensitive sort. You can also direct Sort-Object to display only the objects with a unique value for a particular property.

Parameters

-CaseSensitive

Indicates that the sort should be case sensitive. By default, sorting is not case sensitive.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Culture <string>

Specifies the cultural configuration to use when sorting.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Descending

Sorts the objects in descending order. The default is ascending order.

The Descending parameter applies to all properties. To sort by some properties in

ascending order and others in descending order, you must specify their property values by using a hash table. For details, see the examples.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be sorted.

When you use the InputObject parameter to submit a collection of items, Sort-Object receives one object that represents the collection. Because one object cannot be sorted, Sort-Object returns the entire collection unchanged.

To sort objects, pipe them to Sort-Object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Property <Object[]>

Specifies the properties to use when sorting. Objects are sorted based on the values of these properties. Enter the names of the properties. Wildcards are permitted.

If you specify multiple properties, the objects are first sorted by the first property. If more than one object has the same value for the first property, those objects are sorted by the second property. This process continues until there are no more specified properties or no groups of objects.

If you do not specify properties, the cmdlet sorts based on default properties for the object type.

The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

-- Expression <string> or <script block>

-- Ascending <Boolean>

-- Descending <Boolean>

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | true

-Unique

Eliminates duplicates and returns only the unique members of the collection. You can use this parameter instead of using the Get-Unique cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe the objects to be sorted to Sort-Object.
Outputs | System.Management.Automation.PSObject Sort-Object returns the sorted objects.

Notes

Sort-Object sorts objects based on the properties that you specify or the default sort properties for objects of that type.

If an object does not have one of the specified properties, the property value for that object is interpreted by the cmdlet as NULL and is placed at the end of the sort order.

When sorting objects, Sort-Object uses the Compare method for each property. If a property does not implement IComparable, the cmdlet converts the property value to a string and uses the Compare method for System.String.

The Sort-Object cmdlet sorts objects in ascending or descending order based on the values of properties of the object.

If you sort on a property whose value is an enumeration, Sort-Object sorts the enumeration values in numeric order; it does not sort the enumeration member names. For example, if you sort services by status, services with a status of "Stopped" appear before services with a status of "Running", because the value of Status is a ServiceControllerStatus enumeration, in which "Stopped" has a value of 1 and "Running" has a value of 4.

Example 1

C:\PS>get-childitem | sort-object

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         9/13/2005   4:24 PM          0 0
-a---          9/6/2005   4:19 PM         12 a.csv
-a---         9/21/2005   3:49 PM        529 a.Ps
-a---         8/22/2005   4:14 PM         22 a.pl
-a---         9/27/2005  10:33 AM         24 a.txt
-a---         9/15/2005  10:31 AM        398 a.vbs
-a---         7/21/2005  12:39 PM      37066 a.xml
-a---         8/28/2005  11:30 PM       5412 a.xslt
-a---        10/25/2005   1:59 PM        125 AdamTravel.txt
-a---         7/21/2005   9:49 AM         59 add2Num.Ps
-a---         8/29/2005   5:42 PM       7111 add-content.xml
-a---         9/21/2005  12:46 PM       8771 aliens.Ps
-a---         8/10/2005   2:10 PM        798 array.xml
-a---          8/4/2004   5:00 AM        110 AUTORUN.INF
-a---          9/6/2005   4:20 PM        245 b.csv
...

Description
-----------
This command sorts the subdirectories and files in the current directory. Because no properties are specified, the files and directories are sorted in ascending alphabetical order by their default sort property, Name.

Example 2

C:\PS>get-childitem | sort-object -property length

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         12/3/2006   5:35 PM          2 pref.txt
-a---          9/6/2006   3:33 PM         15 count.txt
-a---         7/26/2006  10:01 AM         30 filenoext
-a---         8/18/2006   9:02 AM         52 temp.ps1
-a---         8/18/2006   9:02 AM         52 temp.msh
-a---          9/6/2006   3:33 PM         56 fivewords.txt
-a---         7/26/2006   9:28 AM         80 date.csv
-a---         7/29/2006   7:15 PM         84 test2.txt
-a---         7/29/2006   7:15 PM         84 test.ps1

Description
-----------
This command displays the files in the current directory in ascending order by file length.

Example 3

C:\PS>get-process | sort-object -property WS | select-object -last 5

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
   1105      25    44236      18932   197    93.81   2032 iexplore
   2526      66    37668      36836   221   393.27    868 svchost
    974      19    22844      45928   371    88.39   3952 WINWORD
   1371      22    42192      61872   323    75.75   1584 INFOPATH
   2145      58    93088      70680   619   396.69   3908 OUTLOOK

Description
-----------
This command displays the five processes on the computer with the greatest memory use based on the size of their working sets.

The command uses the Get-Process cmdlet to get a list of processes. It uses a pipeline operator (|) to send the results to the Sort-Object cmdlet, which sorts the objects in working-set order.

Another pipeline operator sends the results to the Select-Object, which displays only the last five items in the list.

Example 4

C:\PS>get-history | sort-object -descending

Id CommandLine
-- -----------
51 get-history | sort -descending
50 get-history | sort -descending
49 get-history | sort -descending
48 get-history | sort -descending
47 get-history | sort -descending
46 get-history | sort -descending
45 get-history | sort -descending
44 cd $pshome
43 get-childitem | sort-object
42 gci *.txt

Description
-----------
This command sorts HistoryInfo objects using the Id property as the default key.

Example 5

C:\PS>C:\PS> get-service | sort-object -property `
@{Expression="Status";Descending=$true}, `
@{Expression="DisplayName";Descending=$false}

Status   Name               DisplayName
------   ----               -----------
Running  ALG                Application Layer Gateway Service
Running  Ati HotKey Poller  Ati HotKey Poller
Running  wuauserv           Automatic Updates
Running  BITS               Background Intelligent Transfer Ser...
Running  Client for NFS     Client for NFS
...
Stopped  clr_optimizatio... .NET Runtime Optimization Service v...
Stopped  Alerter            Alerter
Stopped  AppMgmt            Application Management
Stopped  aspnet_state       ASP.NET State Service
Stopped  ATI Smart          ATI Smart
Stopped  ClipSrv            ClipBook

Description
-----------
This command displays the services on the computer in descending Status order and ascending DisplayName order.

The command uses the Get-Service cmdlet to get the services on the computer. It uses a pipeline operator (|) to send services to the Sort-Object cmdlet.

To sort one property in ascending order and another property in descending order, the command uses a hash table for the value of the Property parameter. The hash table uses an Expression key to specify the property name and an Ascending or Descending key to specify the sort order.

The resulting display, which sorts the Status values in descending order, lists properties with a Status value of "Running" before those with a Status value of "Stopped". When sorted in ascending order, "Stopped" appears before "Running", because Status is an enumerated property in which the value of "Stopped" (1) is less than the value of "Running" (4).

Example 6

C:\PS>get-childitem *.txt | sort-object -property @{Expression={$_.LastWriteTime - $_.CreationTime}; Ascending=$false} | Format-Table LastWriteTime, CreationTime

LastWriteTime                           CreationTime
-------------                           ------------
2/21/2006 10:22:20 AM                   10/3/2005 4:19:40 PM
2/27/2006 8:14:24 AM                    2/23/2006 10:41:08 PM
2/24/2006 1:26:19 PM                    2/23/2006 11:23:36 PM
1/5/2006 12:01:35 PM                    1/5/2006 11:35:30 AM
2/24/2006 9:25:40 AM                    2/24/2006 9:22:24 AM
2/24/2006 9:40:01 AM                    2/24/2006 9:39:41 AM
2/21/2006 10:21:30 AM                   2/21/2006 10:21:30 AM

Description
-----------
This command sorts text files in descending order by the time span between CreationTime and LastWriteTime.

Example 7

C:\PS>get-content servers.txt

localhost
test01
server01
server02
localhost
server01

C:\PS> get-content servers.txt | sort-object -unique
localhost
server01
server02
test01

Description
-----------
These commands sort the names of servers in a text file. The second command uses the Sort-Object cmdlet with the Unique parameter to return a sorted list without duplicates.

See Also

  • Group-Object


Split-Path

Returns the specified part of a path.

Syntax

Split-Path [-IsAbsolute] [-Path] <string[]> [-Credential <PSCredential>] [-LiteralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>]

Split-Path [-Leaf] [-Path] <string[]> [-Credential <PSCredential>] [-LiteralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>]

Split-Path [-NoQualifier] [-Path] <string[]> [-Credential <PSCredential>] [-LiteralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>]

Split-Path [-Parent] [-Path] <string[]> [-Credential <PSCredential>] [-LiteralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>]

Split-Path [-Qualifier] [-Path] <string[]> [-Credential <PSCredential>] [-LiteralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>]

Description

The Split-Path cmdlet returns only the specified part of a path, such as the parent directory, a child directory, or a file name. It also can display the items that are referenced by the split path and tell whether the path is relative or absolute.

You can use this cmdlet to display or submit only a selected part of a path.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-IsAbsolute

Returns TRUE if the path is absolute and FALSE if it is relative. An absolute path has a length greater than zero and does not use a dot ( . ) to indicate the current path.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Leaf

Returns only the last item or container in the path. For example, in the path "C:\Test\Logs\Pass1.log", it returns only "Pass1.log".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies the paths to be split. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-NoQualifier

Returns the path without the qualifier. For the FileSystem or registry providers, the qualifier is the drive of the provider path, such as C: or HKCU:. For example, in the path "C:\Test\Logs\Pass1.log", it returns only "\Test\Logs\Pass1.log".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Parent

Returns only the parent containers of the item or of the container specified by the path. For example, in the path "C:\Test\Logs\Pass1.log", it returns "C:\Test\Logs". The Parent parameter is the default split location parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies the paths to be split. Wildcards are permitted. If the path includes spaces, enclose it in quotation marks. You can also pipe a path to Split-Path.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Qualifier

Returns only the qualifier of the specified path. For the FileSystem or registry providers, the qualifier is the drive of the provider path, such as C: or HKCU:.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Resolve

Displays the items that are referenced by the resulting split path instead of displaying the path elements.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path to Split-Path.
Outputs | System.String The Split-Path cmdlet returns text strings. When you use the Resolve parameter, Split-Path returns a string that describes the location of the items; it does not return objects that represent the items, such as a FileInfo or RegistryKey object.

Notes

The split location parameters (Qualifier, Parent, Leaf, and NoQualifier) are exclusive. You can use only one in each command.

The cmdlets that contain the Path noun (the Path cmdlets) manipulate path names and return the names in a concise format that all Windows PowerShell providers can interpret. They are designed for use in programs and scripts where you want to display all or part of a path name in a particular format. Use them like you would use Dirname, Normpath, Realpath, Join, or other path manipulators.

You can use the Path cmdlets with several providers, including the FileSystem, Registry, and Certificate providers.

The Split-Path cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>split-path "HKCU:\Software\Microsoft" -qualifier

HKCU:

Description
-----------
This command returns only the qualifier (the drive) of the path.

Example 2

C:\PS>split-path "C:\Test\Logs\*.log" -leaf -resolve

Pass1.log
Pass2.log
...

Description
-----------
This command displays the files that are referenced by the split path. Because this path is split to the last item (the "leaf"), only the file names of the paths are displayed.

The Resolve parameter tells Split-Path to display the items that the split path references, instead of displaying the split path.

Like all Split-Path commands, this command returns strings. It does not return FileInfo Objects representing the files.

Example 3

C:\PS>split-path "C:\WINDOWS\system32\WindowsPowerShell\V1.0\about_*.txt"

C:\WINDOWS\system32\WindowsPowerShell\V1.0

Description
-----------
This command returns only the parent containers of the path. Because it does not include any parameters to specify the split, Split-Path uses the split location default, which is Parent.

Example 4

C:\PS>split-path ".\My Pictures\*.jpg" -IsAbsolute

False

Description
-----------
This command determines whether the path is relative or absolute. In this case, because the path is relative to the current directory, which is represented by a dot (.), it returns FALSE ($false).

Example 5

C:\PS>set-location (split-path $profile)

PS C:\Documents and Settings\juneb\My Documents\WindowsPowerShell>

Description
-----------
This command changes your location to the directory that contains the Windows PowerShell profile.
The command in parentheses uses the Split-Path cmdlet to return only the parent of the path stored in the built-in $Profile variable. (The Parent parameter is the default split location parameter, so you can omit it from the command.) The parentheses direct Windows PowerShell to execute the command first. This is a handy way to navigate to a directory with a long path name.

Example 6

C:\PS>'C:\Documents and Settings\User01\My Documents\My Pictures' | split-path

C:\Documents and Settings\User01\My Documents

Description
-----------
This command uses a pipeline operator (|) to send a path to the Split-Path cmdlet. The path is enclosed in quotation marks to indicate that it is a single token.

See Also

  • about_Providers
  • Test-Path
  • Convert-Path
  • Resolve-Path
  • Join-Path


Start-Job

Starts a Windows PowerShell background job.

Syntax

Start-Job [-ScriptBlock] <scriptblock> [[-InitializationScript] <scriptblock>] [-ArgumentList <Object[]>] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-Credential <PSCredential>] [-InputObject <psobject>] [-Name <string>] [-RunAs32] [<CommonParameters>]

Start-Job [[-FilePath] <string>] [[-InitializationScript] <scriptblock>] [-ArgumentList <Object[]>] [-Authentication {<Default> | <Basic> | <Negotiate> | <NegotiateWithImplicitCredential> | <Credssp> | <Digest> | <Kerberos>}] [-Credential <PSCredential>] [-InputObject <psobject>] [-Name <string>] [-RunAs32] [<CommonParameters>]

Description

The Start-Job cmdlet starts a Windows PowerShell background job on the local computer.

A Windows PowerShell background job runs a command "in the background" without interacting with the current session. When you start a background job, a job object is returned immediately, even if the job takes an extended time to complete. You can continue to work in the session without interruption while the job runs.

The job object contains useful information about the job, but it does not contain the job results. When the job completes, use the Receive-Job cmdlet to get the results of the job. For more information about background jobs, see about_Jobs.

To run a background job on a remote computer, use the AsJob parameter that is available on many cmdlets, or use the Invoke-Command cmdlet to run a Start-Job command on the remote computer. For more information, see about_Remote_Jobs.

Parameters

-ArgumentList <Object[]>

Specifies the arguments (parameter values) for the script that is specified by the FilePath parameter.

Because all of the values that follow the ArgumentList parameter name are interpreted as being values of ArgumentList, the ArgumentList parameter should be the last parameter in the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationMechanism>

Specifies the mechanism that is used to authenticate the user's credentials. Valid values are Default, Basic, Credssp, Digest, Kerberos, Negotiate, and NegotiateWithImplicitCredential. The default value is Default.

CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows.

For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in MSDN.

CAUTION: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one from the Get-Credential cmdlet.

Required? | false
Position? | named
Default Value | Current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilePath <string>

Runs the specified local script as a background job. Enter the path and file name of the script or pipe a script path to Start-Job. The script must reside on the local computer or in a directory that the local computer can access.

When you use this parameter, Windows PowerShell converts the contents of the specified script file to a script block and runs the script block as a background job.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InitializationScript <scriptblock>

Specifies commands that run before the job starts. Enclose the commands in braces ( { } ) to create a script block.

Use this parameter to prepare the session in which the job runs. For example, you can use it to add functions, snap-ins, and modules to the session.

Required? | false
Position? | 2
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies input to the command. Enter a variable that contains the objects, or type a command or expression that generates the objects.

In the value of the ScriptBlock parameter, use the $input automatic variable to represent the input objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string>

Specifies a friendly name for the new job. You can use the name to identify the job to other job cmdlets, such as Stop-Job.

The default friendly name is Job#, where "#" is an ordinal number that is incremented for each job.

Required? | false
Position? | named
Default Value | Job<number>
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-RunAs32

Runs the job in a 32-bit process.

Use this parameter to force the job to run in a 32-bit process on a 64-bit operating system.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ScriptBlock <scriptblock>

Specifies the commands to run in the background job. Enclose the commands in braces ( { } ) to create a script block. This parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a file path to Start-Job.
Outputs | System.Management.Automation.RemotingJob Start-Job returns an object that represents the job that it started.

Notes

To run in the background, Start-Job runs in its own session within the current session. When you use the Invoke-Command cmdlet to run a Start-Job command in a session on a remote computer, Start-Job runs in a session within the remote session.

Example 1

C:\PS>start-job -scriptblock {get-process}

C:\PS> start-job -command "get-process"

Id    Name  State    HasMoreData  Location   Command
---   ----  -----    -----------  --------   -------
1     Job1  Running  True         localhost  get-process

Description
-----------
This command starts a background job that runs a Get-Process command. The command returns a job object with information about the job. The command prompt returns immediately so that you can work in the session while the job runs in the background.

Example 2

C:\PS>$jobWRM = invoke-command -computerName (get-content servers.txt) -scriptblock {get-service winrm} -jobname WinRM -throttlelimit 16 -AsJob

This command uses the Invoke-Command cmdlet and its AsJob parameter to start a background job that runs a "get-service winrm" command on numerous computers. Because the command is running on a server with substantial network traffic, the command uses the ThrottleLimit parameter of Invoke-Command to limit the number of concurrent commands to 16.

The command uses the ComputerName parameter to specify the computers on which the job runs. The value of the ComputerName parameter is a Get-Content command that gets the text in the Servers.txt file, a file of computer names in a domain.

The command uses the ScriptBlock parameter to specify the command and the JobName parameter to specify a friendly name for the job.

Example 3

C:\PS>$j = start-job -scriptblock {get-eventlog -log system} -credential domain01\user01

C:\PS> $j | format-list -property *

HasMoreData   : True
StatusMessage :
Location      : localhost
Command       : get-eventlog -log system
JobStateInfo  : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : 2d9d775f-63e0-4d48-b4bc-c05d0e177f34
Id            : 1
Name          : Job1
ChildJobs     : {Job2}
Output        : {}
Error         : {}
Progress      : {}
Verbose       : {}
Debug         : {}
Warning       : {}
StateChanged  :

C:\PS> $j.JobStateInfo.state
Completed

C:\PS> $results = receive-job -job $j

C:\PS> $results
Index Time          Type        Source                EventID Message
----- ----          ----        ------                ------- -------
84366 Feb 18 19:20  Information Service Control M...     7036 The description...
84365 Feb 18 19:16  Information Service Control M...     7036 The description...
84364 Feb 18 19:10  Information Service Control M...     7036 The description...
...

Description
-----------
These commands manage a background job that gets all of the events from the System log in Event Viewer. The job runs on the local computer.

The first command uses the Start-Job cmdlet to start the job. It uses the Credential parameter to specify the user account of a user who has permission to run the job on the computer. Then it saves the job object that Start-Job returns in the $j variable.

At this point, you can resume your other work while the job completes.

The second command uses a pipeline operator (|) to pass the job object in $j to the Format-List cmdlet. The Format-List command uses the Property parameter with a value of all (*) to display all of the properties of the job object in a list.

The third command displays the value of the JobStateInfo property. This contains the status of the job.

The fourth command uses the Receive-Job cmdlet to get the results of the job. It stores the results in the $results variable.

The final command displays the contents of the $results variable.

Example 4

C:\PS>start-job -filepath c:\scripts\sample.ps1

This command runs the Sample.ps1 script as a background job.

Example 5

C:\PS>start-job -name WinRm -scriptblock {get-process winrm}

This command runs a background job that gets the WinRM process on the local computer. The command uses the ScriptBlock parameter to specify the command that runs in the background job. It uses the Name parameter to specify a friendly name for the new job.

Example 6

C:\PS>start-job -name GetMappingFiles -initializationScript {import-module MapFunctions} -scriptblock {Get-Map -name * | set-content D:\Maps.tif} -runAs32

This command starts a job that collects a large amount of data and saves it in a .tif file. The command uses the InitializationScript parameter to run a script block that imports a required module. It also uses the RunAs32 parameter to run the job in a 32-bit process even if the computer has a 64-bit operating system.

See Also

  • about_Jobs
  • about_Job_Details
  • about_Remote_Jobs
  • Get-Job
  • Receive-Job
  • Wait-Job
  • Stop-Job
  • Remove-Job
  • Invoke-Command


Start-Process

Starts one or more processes on the local computer.

Syntax

Start-Process [-Verb <string>] [-WindowStyle {<Normal> | <Hidden> | <Minimized> | <Maximized>}] [-FilePath] <string> [[-ArgumentList] <string[]>] [-Credential <pscredential>] [-LoadUserProfile <Boolean>] [-NoNewWindow] [-PassThru] [-RedirectStandardError <string>] [-RedirectStandardInput <string>] [-RedirectStandardOutput <string>] [-UseNewEnvironment] [-Wait] [-WorkingDirectory <string>] [<CommonParameters>]

Description

Starts one or more processes on the local computer. To specify the program that runs in the process, enter an executable file or script file, or a file that can be opened by using a program on the computer. If you specify a non-executable file, Start-Process starts the program that is associated with the file, much like the Invoke-Item cmdlet.

You can use the parameters of Start-Process to specify options, such as loading a user profile, starting the process in a new window, or using alternate credentials.

Parameters

-ArgumentList <string[]>

Specifies parameters or parameter values to use when starting the process. The parameter name ("Arguments") is optional.

Required? | false
Position? | 2
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <pscredential>

Specifies a user account that has permission to perform this action. Type a user-name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one from the Get-Credential cmdlet. By default, the cmdlet uses the credentials of the current user.

Required? | false
Position? | named
Default Value | Current user.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilePath <string>

Specifies the path (optional) and file name of the program that runs in the process. Enter the name of an executable file or of a document, such as a .txt or .doc file, that is associated with a program on the computer. This parameter is required.

If you specify only a file name, use the WorkingDirectory parameter to specify the path.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LoadUserProfile <Boolean>

Loads the Windows user profile stored in the HKEY_USERS registry key for the current user. The default value is FALSE.

This parameter does not affect the Windows PowerShell profiles. (See about_Profiles.)

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoNewWindow

Prevents the process from running in a new window. By default, the process runs in a new window.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PassThru

Returns a process object for each process that the cmdlet started. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RedirectStandardError <string>

Sends any errors generated by the process to a file that you specify. Enter the path and file name. By default, the errors are displayed in the console.

Required? | false
Position? | named
Default Value | Errors are displayed in the console
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RedirectStandardInput <string>

Reads input from the specified file. Enter the path and file name of the input file. By default, the process gets its input from the keyboard.

Required? | false
Position? | named
Default Value | Keyboard
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RedirectStandardOutput <string>

Sends the output generated by the process to a file that you specify. Enter the path and file name. By default, the output is displayed in the console.

Required? | false
Position? | named
Default Value | FALSE
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseNewEnvironment

Use new environment variables specified for the process. By default, the started process runs with the environment variables specified for the computer and user.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Verb <string>

Specifies a verb to be used when starting the process, such as Edit, Open, or Print.

Each file type has a set of verbs that you can use. To find the verbs that can be used with the process, use the Verbs property of the object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Wait

Waits for the specified process to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the process completes.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WindowStyle <ProcessWindowStyle>

Specifies the state of the windows used for the process. Valid values are Normal, Hidden, Minimized, and Maximized. The default value is Normal.

Required? | false
Position? | named
Default Value | Normal
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WorkingDirectory <string>

Specifies the location of the executable file or document that runs in the process. The default is the current directory.

Required? | false
Position? | named
Default Value | Current directory
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to Start-Process.
Outputs | None or System.Diagnostics.Process When you use the PassThru parameter, Start-Process generates a System.Diagnostics.Process. Otherwise, this cmdlet does not return any output.

Notes

This cmdlet is implemented by using the Start method of the System.Diagnostics,Process class. For more information about this method, see "Process.Start Method" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143602.

Example 1

C:\PS>start-process sort.exe

This command starts a process that uses the Sort.exe file in the current directory. The command uses all of the default values, including the default window style, working directory, and credentials.

Example 2

C:\PS>start-process myfile.txt -workingdirectory "C:\PS-Test" -verb Print

This command starts a process that prints the C:\PS-Test\MyFile.txt file.

Example 3

C:\PS>start-process Sort.exe -RedirectStandardInput Testsort.txt -RedirectStandardOutput Sorted.txt -RedirectStandardError SortError.txt -UseNewEnvironment

This command starts a process that sorts items in the Testsort.txt file and returns the sorted items in the Sorted.txt files. Any errors are written to the SortError.txt file.

The UseNewEnvironment parameter specifies that the process runs with its own environment variables.

Example 4

C:\PS>start-process notepad -wait -windowstyle Maximized

This command starts the Notepad process. It maximizes the window and retains the window until the process completes.

See Also

  • Start-Service
  • Get-Process
  • Stop-Process
  • Wait-Process
  • Debug-Process


Start-Service

Starts one or more stopped services.

Syntax

Start-Service [-Name] <string[]> [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Start-Service -DisplayName <string[]> [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Start-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Start-Service cmdlet sends a start message to the Windows Service Controller for each of the specified services. If a service is already running, the message is ignored without error. You can specify the services by their service names or display names, or you can use the InputObject parameter to supply a service object representing the services that you want to start.

Parameters

-DisplayName <string[]>

Specifies the display names of the services to be started. Wildcards are permitted.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Starts only the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ServiceController[]>

Specifies ServiceController objects representing the services to be started. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the service names for the service to be started.

The parameter name is optional. You can use "-Name" or its alias, "-ServiceName", or you can omit the parameter name.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the service. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.ServiceProcess.ServiceController, System.String You can pipe objects that represent the services or strings that contain the service names to Start-Service.
Outputs | None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Start-Service generates a System.ServiceProcess.ServiceController object representing the service. Otherwise, this cmdlet does not generate any output.

Notes

You can also refer to Start-Service by its built-in alias, "sasv". For more information, see about_Aliases.

Start-Service can control services only when the current user has permission to do so. If a command does not work correctly, you might not have the required permissions.

To find the service names and display names of the services on your system, type "Get-Service". The service names appear in the Name column, and the display names appear in the DisplayName column.

You can start only the services that have a start type of "Manual" or "Automatic". You cannot start the services with a start type of "Disabled". If a Start-Service command fails with the message "Cannot start service <service-name> on computer," use a Get-WmiObject command to find the start type of the service and, if necessary, use a Set-Service command to change the start type of the service.

Some services, such as Performance Logs and Alerts (SysmonLog) stop automatically if they have no work to do. When Windows PowerShell starts a service that stops itself almost immediately, it displays the following message: "Service <display-name> start failed."

Example 1

C:\PS>start-service -name eventlog

This command starts the EventLog service on the local computer. It uses the Name parameter to identify the service by its service name.

Example 2

C:\PS>start-service -displayname *remote* -whatif

This command tells what would happen if you started the services with a display name that includes "remote". It uses the DisplayName parameter to specify the services by their display name instead of by their service name. And, it uses the WhatIf parameter to tell what would happen if the command were executed instead of executing the command.

Example 3

C:\PS>$s = get-service wmi

C:\PS>start-service -InputObject $s -passthru | format-list >> services.txt

These commands start the Windows Management Instrumentation (WMI) service on the computer and add a record of the action to the services.txt file. The first command uses the Get-Service cmdlet to get an object representing the WMI service and store it in the $s variable.

The second command uses the Start-Service cmdlet to start the WMI service. It identifies the service by using the InputObject parameter to pass the $s variable containing the WMI service object to Start-Service. Then, it uses the PassThru parameter to create an object that represents the starting of the service. Without this parameter, Start-Service does not create any output.

The pipeline operator (|) passes the object that Start-Service creates to the Format-List cmdlet, which formats the object as a list of its properties. The append redirection operator (>>) redirects the output to the services.txt file, where it is added to the end of the existing file.

Example 4

C:\PS># start-service

Description
-----------
This series of commands shows how to start a service when the start type of the service is "Disabled". The first command, which uses the Start-Service cmdlet to start the Telnet service (tlntsvr), fails.

C:\PS>start-service tlntsvr

Start-Service : Service 'Telnet (TlntSvr)' cannot be started due to the    following error: Cannot start service TlntSvr on computer '.'.
At line:1 char:14
+ start-service  <<<< tlntsvr

The second command uses the Get-WmiObject cmdlet to get the Tlntsvr service. This command retrieves an object with the start type property in the StartMode field. The resulting display reveals that the start type of the Tlntsvr service is "Disabled".

C:\PS> get-wmiobject win32_service | where-object {$_.Name -eq "tlntsvr"}

ExitCode  : 0
Name      : TlntSvr
ProcessId : 0
StartMode : Disabled
State     : Stopped
Status    : OK

The next command uses the Set-Service cmdlet to change the start type of the Tlntsvr service to "Manual".

C:\PS> set-service tlntsvr -startuptype manual

Now, we can resubmit the Start-Service command. This time, the command succeeds.

C:\PS> start-service tlntsvr

To verify that the command succeeded, use Get-Service.

See Also

  • Get-Service
  • Suspend-Service
  • Stop-Service
  • Restart-Service
  • Resume-Service
  • Set-Service
  • New-Service


Start-Sleep

Suspends the activity in a script or session for the specified period of time.

Syntax

Start-Sleep -Milliseconds <int> [<CommonParameters>]

Start-Sleep [-Seconds] <int> [<CommonParameters>]

Description

The Start-Sleep cmdlet suspends the activity in a script or session for the specified period of time. You can use it for many tasks, such as waiting for an operation to complete or pausing before repeating an operation.

Parameters

-Milliseconds <int>

Specifies how long the resource sleeps in milliseconds. The parameter can be abbreviated as "-m".

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Seconds <int>

Specifies how long the resource sleeps in seconds. You can omit the parameter name ("Seconds"), or you can abbreviate it as "-s".

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Int32 You can pipe the number of seconds to Start-Sleep.
Outputs | None This cmdlet does not return any output.

Notes

You can also refer to Start-Sleep by its built-in alias, "sleep". For more information, see about_Aliases.

Example 1

C:\PS>Start-Sleep -s 15

This command makes all commands in the session sleep for 15 seconds.

Example 2

C:\PS>Start-Sleep -m 500

This command makes all the commands in the session sleep for one-half of a second (500 milliseconds).


Start-Transaction

Starts a transaction.

Syntax

Start-Transaction [-Independent] [-RollbackPreference {<Error> | <TerminatingError> | <Never>}] [-Timeout <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Start-Transaction cmdlet starts a transaction, which is a series of commands that are managed as a unit. A transaction can be completed ("committed"), or it can be completely undone ("rolled back") so that any data changed by the transaction is restored to its original state. Because the commands in a transaction are managed as a unit, either all commands are committed or all commands are rolled back.

By default, transactions are rolled back automatically if any command in the transaction generates an error, but you can use the RollbackPreference parameter to change this behavior.

The cmdlets used in a transaction must be designed to support transactions. Cmdlets that support transactions have a UseTransaction parameter. To perform transactions in a provider, the provider must support transactions. The Windows PowerShell Registry Provider in Windows Vista and later versions of Windows supports transactions. You can also use the Microsoft.PowerShell.Commands.Management.TransactedString class to include expressions in transactions on any version of Windows that supports Windows PowerShell. Other Windows PowerShell providers can also support transactions.

Only one transaction can be active at a time. If you start a new, independent transaction while a transaction is in progress (neither completed nor undone), the new transaction becomes the active transaction, and you must commit or roll back the new transaction before making any changes to the original transaction.

The Start-Transaction cmdlet is one of a set of cmdlets that support the transactions feature in Windows PowerShell. For more information, see about_Transactions.

Parameters

-Independent

Starts a transaction that is independent of any transactions in progress. By default, if you use Start-Transaction while another transaction is in progress, a new subscriber is added to the transaction in progress. This parameter has an effect only when a transaction is already in progress in the session.

By default, if you use Start-Transaction while a transaction is in progress, the existing transaction object is reused and the subscriber count is incremented. The effect is much like joining the original transaction. An Undo-Transaction command rolls back the entire the transaction. To complete the transaction, you must enter a Complete-Transaction command for each subscriber. Because most transactions that are in progress at the same time are related, the default is sufficient for most uses.

If you use the Independent parameter, a new transaction is created that can be completed or undone without affecting the original transaction. However, because only one transaction can be active at a time, you must complete or roll back the new transaction before resuming work on the original transaction.

Required? | false
Position? | named
Default Value | Reuse the original transaction object.
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RollbackPreference <RollbackSeverity>

Specifies the conditions under which a transaction is automatically rolled back. The default value is "Error".

Valid values are:

-- Error: The transaction is rolled back automatically if a terminating or non-terminating error occurs. "Error" is the default.

-- Terminating error: The transaction is rolled back automatically if a terminating error occurs.

-- Never: The transaction is never rolled back automatically.

Required? | false
Position? | named
Default Value | Error
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Timeout <int>

Specifies the maximum time, in minutes, that the transaction is active. When the time-out expires, the transaction is automatically rolled back.

By default, there is no time-out for transactions that are started at the command line. When transactions are started by a script, the default time-out is 30 minutes.

Required? | false
Position? | named
Default Value | No timeout (infinite)
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not generate any output.

Example 1

C:\PS>cd hkcu:\software

PS HKCU:\software> start-transaction

PS HKCU:\software> new-item MyCompany -UseTransaction

PS HKCU:\software> new-itemproperty MyCompany -name MyKey -value 123 -UseTransaction

PS HKCU:\software> undo-transaction

These commands start and then roll back a transaction. Because the transaction is rolled back, no changes are made to the registry.

Example 2

C:\PS>cd hkcu:\software

PS HKCU:\software> start-transaction

PS HKCU:\software> new-item MyCompany -UseTransaction

PS HKCU:\software> new-itemproperty MyCompany -name MyKey -value 123 -UseTransaction

PS HKCU:\software> complete-transaction

These commands start and then complete a transaction. No changes are made to the registry until the Complete-Transaction command is used.

Example 3

C:\PS>cd HKCU:\software
PS HKCU:\software> start-transaction
PS HKCU:\software> new-item -path NoPath -name MyCompany -UseTransaction
PS HKCU:\software> new-item -path . -name MyCompany -UseTransaction

PS HKCU:\software> start-transaction -RollbackPreference never
PS HKCU:\software> new-item -path NoPath -name MyCompany -UseTransaction
PS HKCU:\software> new-item -path . -name MyCompany -UseTransaction

# Start-Transaction (-rollbackpreference error)

PS HKCU:\software> start-transaction
PS HKCU:\software> new-item -path NoPath -Name MyCompany -UseTransaction
New-Item : The registry key at the specified path does not exist.
At line:1 char:9
+ new-item <<<<  -path NoPath -Name MyCompany -UseTransaction

PS HKCU:\software> new-item -path . -name MyCompany -UseTransaction
New-Item : Cannot use transaction. The transaction has been rolled back or has timed out.
At line:1 char:9
+ new-item <<<<  -path . -name MyCompany -UseTransaction

# Start-Transaction (-rollbackpreference never)
PS HKCU:\software> start-transaction -RollbackPreference never
PS HKCU:\software> new-item -path NoPath -name MyCompany -UseTransaction
New-Item : The registry key at the specified path does not exist.
At line:1 char:9
+ new-item <<<<  -path NoPath -name MyCompany -UseTransaction

PS HKCU:\software> new-item -path . -name MyCompany -UseTransaction
  Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
  0   0 MyCompany                      {}

PS HKCU:\Software> complete-transaction
# Succeeds

Description
-----------
This example demonstrates the effect of changing the RollbackPreference parameter value.

In the first set of commands, the Start-Transaction command does not use the RollbackPreference parameter. As a result, the default value ("Error") is used. When an error occurs in a transaction command (the specified path does not exist), the transaction is automatically rolled back.

In the second set of commands, the Start-Transaction command uses the RollbackPreference parameter with a value of "Never". As a result, when an error occurs in a transaction command, the transaction is still active and can be completed successfully.

Because most transactions must be performed without error, the default value of the RollbackPreference parameter is typically preferred.

Example 4

C:\PS>cd HKCU:\software

PS HKCU:\software> start-transaction
PS HKCU:\software> new-item MyCompany -UseTransaction

PS HKCU:\software> start-transaction
PS HKCU:\software> get-transaction
PS HKCU:\software> new-item MyCompany2 -UseTransaction

PS HKCU:\software> complete-transaction
PS HKCU:\software> complete-transaction

PS HKCU:\Software> Get-Transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   ------
Error                2                 Active

Description
-----------
This example shows the effect of using the Start-Transaction command while a transaction is in progress. The effect is much like joining the transaction in progress.

Although this is a simplified command, this scenario commonly occurs when the transaction involves running a script that includes a complete transaction.

The first Start-Transaction command starts the transaction. The first New-Item command is part of the transaction.

The second Start-Transaction command adds a new subscriber to the transaction. The Get-Transaction command now returns a transaction with a subscriber count of 2. The second New-Item command is part of the same transaction.

No changes are made to the registry until the entire transaction is completed. To complete the transaction, you must enter two Complete-Transaction commands, one for each subscriber. If you were to roll back the transaction at any point, the entire transaction would be rolled back for both subscribers.

Example 5

C:\PS>cd HKCU:\software
PS HKCU:\software> start-transaction
PS HKCU:\software> new-item MyCompany -UseTransaction

PS HKCU:\software> start-transaction -independent
PS HKCU:\software> get-transaction
PS HKCU:\software> undo-transaction

PS HKCU:\software> new-itemproperty -path MyCompany -name MyKey -value 123 -UseTransaction
PS HKCU:\software> complete-transaction
PS HKCU:\software> dir my*

PS HKCU:\Software> get-transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   ------
Error                1                 Active

PS HKCU:\software> undo-transaction
PS HKCU:\software> new-itemproperty -path MyCompany -name MyKey -value 123 -UseTransaction

MyKey
-----
123

PS HKCU:\software> complete-transaction
PS HKCU:\software> dir my*

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
  0   1 MyCompany                      {MyKey}

Description
-----------
This example shows the effect of using the Independent parameter of Start-Transaction to start a transaction while another transaction is in progress. In this case, the new transaction is rolled back without affecting the original transaction.

Although the transactions are logically independent, because only one transaction can be active at a time, you must roll back or commit the newest transaction before resuming work on the original transaction.

The first set of commands starts a transaction. The New-Item command is part of the first transaction.

In the second set of commands, the Start-Transaction command uses the Independent parameter. The Get-Transaction command that follows shows the transaction object for the active transaction (the newest one). The subscriber count is equal to 1, showing that the transactions are unrelated.

When the active transaction is rolled back by using an Undo-Transaction command, the original transaction becomes active again.

The New-ItemProperty command, which is part of the original transaction, completes without error, and the original transaction can be completed by using the Complete-Transaction command. As a result, the registry is changed.

Example 6

C:\PS>cd hkcu:\software

PS HKCU:\software> start-transaction
PS HKCU:\software> new-item MyCompany1 -UseTransaction
PS HKCU:\software> new-item MyCompany2
PS HKCU:\software> new-item MyCompany3 -UseTransaction

PS HKCU:\software> dir my*

PS HKCU:\software> complete-transaction
PS HKCU:\software> dir my*

PS HKCU:\Software> dir my*

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
  0   0 MyCompany2                     {}

PS HKCU:\Software> complete-transaction

PS HKCU:\Software> dir my*

   Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property
---  -- ----                           --------
  0   0 MyCompany1                     {}
  0   0 MyCompany2                     {}
  0   0 MyCompany3                     {}

Description
-----------
This example demonstrates that commands that are submitted while a transaction is in progress can be included in the transaction or not included. Only commands that use the UseTransaction parameter are part of the transaction.

The first and third New-Item commands use the UseTransaction parameter. These commands are part of the transaction. Because the second New-Item command does not use the UseTransaction parameter, it is not part of the transaction.

The first "dir" command shows the effect. The second New-Item command is completed immediately, but the first and third New-Item commands are not effective until the transaction is committed.

The Complete-Transaction command commits the transaction. As a result, the second "dir" command shows that all of the new items are added to the registry.

Example 7

C:\PS>start-transaction -timeout 2

# Wait two minutes...

C:\PS> get-transaction

C:\PS> new-item HKCU:\Software\MyCompany -UseTransaction

C:\PS> start-transaction -timeout 2

# Wait two minutes...

C:\PS>> get-transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   -----------
Error                1                 RolledBack

C:\PS> new-item HKCU:\Software\MyCompany -UseTransaction
New-Item : Cannot use transaction. The transaction has been rolled back or has timed out.
At line:1 char:9
+ new-item <<<<  MyCompany -UseTransaction

Description
-----------
This command uses the Timeout parameter of Start-Transaction to start a transaction that must be completed within two minutes. If the transaction is not complete when the timeout expires, it is rolled back automatically.

When the timeout expires, you are not notified, but the Status property of the transaction object is set to RolledBack and commands that use the UseTransaction parameter fail.

See Also

  • about_Transactions
  • Get-Transaction
  • Complete-Transaction
  • Undo-Transaction
  • Use-Transaction


Start-Transcript

Creates a record of all or part of a Windows PowerShell session in a text file.

Syntax

Start-Transcript [[-Path] <string>] [-Append] [-Force] [-NoClobber] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Start-Transcript cmdlet creates a record of all or part of a Windows PowerShell session in a text file. The transcript includes all command that the user types and all output that appears on the console.

Parameters

-Append

Adds the new transcript to the end of an existing file. Use the Path parameter to specify the file.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to append the transcript to an existing read-only file. When used on a read-only file, the cmdlet changes the file permission to read-write. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoClobber

Will not overwrite (replace the contents) of an existing file. By default, if a transcript file exists in the specified path, Start-Transcript overwrites the file without warning.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Path <string>

Specifies a location for the transcript file. Enter a path to a .txt file. Wildcards are not permitted.

If you do not specify a path, Start-Transcript uses the path in the value of the $Transcript global variable. If you have not created this variable, Start-Transcript stores the transcripts in the $Home\My Documents directory as \PowerShell_transcript.<time-stamp>.txt files.

If any of the directories in the path do not exist, the command fails.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe objects to this cmdlet.
Outputs | System.String Start-Transcript returns a string that contains a confirmation message and the path to the output file.

Notes

To stop a transcript, use the Stop-Transcript cmdlet.

To record an entire session, add the Start-Transcript command to your profile. For more information, see about_Profiles.

Example 1

C:\PS>start-transcript

This command starts a transcript in the default file location.

Example 2

C:\PS>start-transcript -path c:\transcripts\transcript0.txt -noclobber

This command starts a transcript in the Transcript0.txt file in C:\transcripts. The NoClobber parameter prevents any existing files from being overwritten. If the Transcript0.txt file already exists, the command fails.

See Also

  • Stop-Transcript


Stop-Computer

Stops (shuts down) local and remote computers.

Syntax

Stop-Computer [[-ComputerName] <string[]>] [[-Credential] <PSCredential>] [-AsJob] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-Force] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Stop-Computer cmdlet shuts down computers remotely. It can also shut down the local computer.

You can use the parameters of Stop-Computer to run the shutdown operations as a background job, to specify the authentication levels and alternate credentials, to limit the concurrent connections that are created to run the command, and to force an immediate shut down.

This cmdlet does not require Windows PowerShell remoting unless you use the AsJob parameter.

Parameters

-AsJob

Runs the command as a background job.

Note: To use this parameter, the local and remote computers must be configured for remoting and, on Windows Vista and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option. For more information, see about_Remote_Requirements".

When you use the AsJob parameter, the command immediately returns an object that represents the background job. You can continue to work in the session while the job completes. The job is created on the local computer and the results from remote computers are automatically returned to the local computer. To manage the job, use the Job cmdlets. To get the job results, use the Receive-Job cmdlet.

For more information about Windows PowerShell background jobs, see about_Jobs and see about_Remote_Jobs.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationLevel>

Specifies the authentication level that is used for the WMI connection. (Stop-Computer uses WMI.) The default value is Packet.

Valid values are:

Unchanged: The authentication level is the same as the previous command.

Default: Windows Authentication.

None: No COM authentication.

Connect: Connect-level COM authentication.

Call: Call-level COM authentication.

Packet: Packet-level COM authentication.

PacketIntegrity: Packet Integrity-level COM authentication.

PacketPrivacy: Packet Privacy-level COM authentication.

Required? | false
Position? | named
Default Value | 4
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Stops the specified computers. The default is the local computer.

Type the NETBIOS name, IP address, or fully qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computername or "localhost".

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter even if your computer is not configured to run remote commands.

Required? | false
Position? | 1
Default Value | .
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one from the Get-Credential cmdlet.

Required? | false
Position? | 2
Default Value | Current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Forces an immediate shut down of the computers.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Impersonation <ImpersonationLevel>

Specifies the impersonation level to use when calling WMI. (Stop-Computer uses WMI.) The default value is "Impersonate".

Valid values are:

Default: Default impersonation.

Anonymous: Hides the identity of the caller.

Identify: Allows objects to query the credentials of the caller.

Impersonate: Allows objects to use the credentials of the caller.

Required? | false
Position? | named
Default Value | Impersonate
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.

The throttle limit applies only to the current command, not to the session or to the computer.

Required? | false
Position? | named
Default Value | 32
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None or System.Management.Automation.RemotingJob When you use the AsJob parameter, the cmdlet returns a job object (System.Management.Automation.RemotingJob). Otherwise, it does not generate any output.

Notes

This cmdlet uses the Win32Shutdown method of the Win32_OperatingSystem WMI class.

Example 1

C:\PS>stop-computer

This command shuts down the local computer.

Example 2

C:\PS>stop-computer -computername Server01, Server02, localhost

This command stops two remote computers, Server01 and Server02, and the local computer, identified as "localhost".

Example 3

C:\PS>$j = stop-computer -computername Server01, Server02 -asjob

C:\PS> $results = $j | receive-job

C:\PS> $results

These commands run a Stop-Computer command as a background job on two remote computers, and then get the results.

The first command uses the AsJob parameter to run the command as a background job. The command saves the resulting job object in the $j variable.

The second command uses a pipeline operator to send the job object in $j to the Receive-Job cmdlet, which gets the job results. The command saves the results in the $results variable.

The third command displays the result saved in the $results variable.

Because the AsJob parameter creates the job on the local computer and automatically returns the results to the local computer, you can run the Receive-Job command as a local command.

Example 4

C:\PS>stop-computer -comp Server01 -impersonation anonymous -authentication PacketIntegrity

This command restarts the Server01 remote computer. The command uses customized impersonation and authentication settings.

Example 5

C:\PS>$s = get-content domain01.txt

C:\PS> $c = get-credential domain01\admin01

C:\PS> stop-computer -computername $s -force -throttlelimit 10 -credential $c

These commands force an immediate shut down of all of the computers in Domain01.

The first command gets a list of computers in the domain and saves it in the $s variable.

The second command gets the credentials of a domain administrator and saves them in the $c variable.

The third command shuts down the computers. It uses ComputerName parameter to submit the list of computers in the $s variable, the Force parameter to force an immediate shutdown, and the Credential parameter to submit the credentials saved in the $c variable. It also uses the ThrottleLimit parameter to limit the command to 10 concurrent connections.

See Also

  • Add-Computer
  • Checkpoint-Computer
  • Remove-Computer
  • Restart-Computer
  • Restore-Computer
  • Test-Connection


Stop-Job

Stops a Windows PowerShell background job.

Syntax

Stop-Job [[-InstanceId] <Guid[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Stop-Job [-Job] <Job[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Stop-Job [[-Name] <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Stop-Job [-Id] <Int32[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Stop-Job [-State {<NotStarted> | <Running> | <Completed> | <Failed> | <Stopped> | <Blocked>}] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Stop-Job cmdlet stops Windows PowerShell background jobs that are in progress. You can use this cmdlet to stop all jobs or stop selected jobs based on their name, ID, instance ID, or state, or by passing a job object to Stop-Job.

You can use Stop-Job to stop jobs that were started by using Start-Job or the AsJob parameter of Invoke-Command. When you stop a background job, Windows PowerShell completes all tasks that are pending in that job queue and then ends the job. No new tasks are added to the queue after this command is submitted.

This cmdlet does not delete background jobs. To delete a job, use Remove-Job.

Parameters

-Id <Int32[]>

Stops jobs with the specified IDs. The default is all jobs in the current session.

The ID is an integer that uniquely identifies the job within the current session. It is easier to remember and type than the InstanceId, but it is unique only within the current session. You can type one or more IDs (separated by commas). To find the ID of a job, type "Get-Job" without parameters.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InstanceId <Guid[]>

Stops only jobs with the specified instance IDs. The default is all jobs.

An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use Get-Job.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Job <Job[]>

Specifies the jobs to be stopped. Enter a variable that contains the jobs or a command that gets the jobs. You can also use a pipeline operator to submit jobs to the Stop-Job cmdlet. By default, Stop-Job deletes all jobs that were started in the current session.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Stops only the jobs with the specified friendly names. Enter the job names in a comma-separated list or use wildcard characters (*) to enter a job name pattern. By default, Stop-Job stops all jobs created in the current session.

Because the friendly name is not guaranteed to be unique, use the WhatIf and Confirm parameters when stopping jobs by name.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | true

-PassThru

Returns an object representing the new background job. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-State <JobState>

Stops only jobs within the specified state. Valid values are NotStarted, Running, Completed, Stopped, Failed, and Blocked.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.RemotingJob You can pipe a job object to Stop-Job.
Outputs | None or System.Management.Automation.RemotingJob When you use the PassThru parameter, Stop-Job returns a job object. Otherwise, this cmdlet does not generate any output.

Example 1

C:\PS>$s = new-pssession -computername Server01 -credential domain01\admin02

C:\PS> $j = invoke-command -session $s -scriptblock {start-job -scriptblock {get-eventlog system}}

C:\PS> invoke-command -session $s -scriptblock {param($j) stop-job -job $j} -ArgumentList $j

This example shows how to use the Stop-Job cmdlet to stop a job that is running on a remote computer.

Because the job was started by using Invoke-Command to run a Start-Job command remotely, the job object is stored on the remote computer, and you must use another Invoke-Command command to run a Stop-Job command remotely. For more information about remote background jobs, see about_Remote_Jobs.

The first command creates a Windows PowerShell session (PSSession) on the Server01 computer and saves the session object in the $s variable. The command uses the credentials of a domain administrator.

The second command uses the Invoke-Command cmdlet to run a Start-Job command in the session. The command in the job gets all of the events in the System event log. The resulting job object is stored in the $j variable.

The third command stops the job. It uses the Invoke-Command cmdlet to run a Stop-Job command in the PSSession on Server01. Because the job objects are stored in $j, which is a variable on the local computer, the command uses the "param" keyword to declare the local variables in the command, and it uses the ArgumentList parameter to supply values for the variables.

When the command completes, the job is stopped and the PSSession in $s is available for use.

Example 2

C:\PS>stop-job -state failed

This command stops all jobs with a State value of "Failed".

Example 3

C:\PS>stop-job -name job1

This command stops the Job1 background job.

Example 4

C:\PS>stop-job -id 1, 3, 4

This command stops three jobs. It identifies them by their IDs.

Example 5

C:\PS>get-job | stop-job

This command stops all the background jobs in the current session.

Example 6

C:\PS>stop-job -state blocked

This command stops all the jobs with a job status of "Blocked".

Example 7

C:\PS>get-job | format-table ID, Name, Command, @{Label="State";Expression={$_.jobstateinfo.state}}, I
nstanceID -auto

Id Name Command                 State  InstanceId
-- ---- -------                 -----  ----------
 1 Job1 start-service schedule Running 05abb67a-2932-4bd5-b331-c0254b8d9146
 3 Job3 start-service schedule Running c03cbd45-19f3-4558-ba94-ebe41b68ad03
 5 Job5 get-service s*         Blocked e3bbfed1-9c53-401a-a2c3-a8db34336adf

C:\PS> stop-job -instanceid e3bbfed1-9c53-401a-a2c3-a8db34336adf

Description
-----------
These commands show how to stop a job based on its instance ID.

The first command uses a Get-Job command to get the jobs in the current session. The command uses a pipeline operator (|) to send the jobs to a Format-Table command, which displays a table of the specified properties of each job. The table includes the Instance ID of each job. It uses a calculated property to display the job state.

The second command uses a Stop-Job command with the InstanceID parameter to stop a selected job.

Example 8

C:\PS>$j = invoke-command -computername Server01 -scriptblock {get-eventlog system} -asjob

C:\PS> $j | stop-job -passthru

Id    Name    State      HasMoreData     Location         Command
--    ----    ----      -----------     --------          -------
5     Job5    Stopped    True            judithh-tablet   get-eventlog system

Description
-----------
This example shows how to use the Stop-Job cmdlet to stop a job that is running on a remote computer.

Because the job was started by using the AsJob parameter of Invoke-Command, the job object is located on the local computer, even though the job runs on the remote computer. As such, you can use a local Stop-Job command to stop the job.

The first command uses the Invoke-Command cmdlet to start a background job on the Server01 computer. The command uses the AsJob parameter to run the remote command as a background job.

This command returns a job object, which is the same job object that Start-Job returns. The command saves the job object in the $j variable.

The second command uses a pipeline operator to send the job in the $j variable to Stop-Job. The command uses the PassThru parameter to direct Stop-Job to return a job object. The job object display confirms that the State of the job is "Stopped".

For more information about remote background jobs, see about_Remote_Jobs.

See Also

  • about_Jobs
  • about_Job_Details
  • about_Remote_Jobs
  • Start-Job
  • Get-Job
  • Receive-Job
  • Wait-Job
  • Remove-Job
  • Invoke-Command


Stop-Process

Stops one or more running processes.

Syntax

Stop-Process [-Id] <Int32[]> [-Force] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Stop-Process -InputObject <Process[]> [-Force] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Stop-Process -Name <string[]> [-Force] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Stop-Process cmdlet stops one or more running processes. You can specify a process by process name or process ID (PID), or pass a process object to Stop-Process. Stop-Process works only on processes running on the local computer.

On Windows Vista and later versions of Windows, to stop a process that is not owned by the current user, you must start Windows PowerShell with the "Run as administrator" option. Also, you are prompted for confirmation unless you use the Force parameter.

Parameters

-Force

Stops the specified processes without prompting for confirmation. By default, Stop-Process prompts for confirmation before stopping any process that is not owned by the current user.

To find the owner of a process, use the Get-WmiMethod cmdlet to get a Win32_Process object that represents the process, and then use the GetOwner method of the object.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Id <Int32[]>

Specifies the process IDs of the processes to be stopped. To specify multiple IDs, use commas to separate the IDs. To find the PID of a process, type "Get-Process". The parameter name ("Id") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InputObject <Process[]>

Stops the processes represented by the specified process objects. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the process names of the processes to be stopped. You can type multiple process names (separated by commas) or use wildcard characters.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the process. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Diagnostics.Process You can pipe a process object to Stop-Process.
Outputs | None or System.Diagnostics.Process When you use the PassThru parameter, Stop-Process returns a System.Diagnostics.Process object that represents the stopped process. Otherwise, this cmdlet does not generate any output.

Notes

You can also refer to Stop-Process by its built-in aliases, "kill" and "spps". For more information, see about_Aliases.

You can also use the properties and methods of the Windows Management Instrumentation (WMI) Win32_Process object in Windows PowerShell. For more information, see Get-WmiObject and the WMI SDK.

When stopping processes, be aware that stopping a process can stop process and services that depend on the process. In an extreme case, stopping a process can stop Windows.

Example 1

C:\PS>stop-process -name notepad

This command stops all instances of the Notepad process on the computer. (Each instance of Notepad runs in its own process.) It uses the Name parameter to specify the processes, all of which have the same name. If you were to use the ID parameter to stop the same processes, you would have to list the process IDs of each instance of Notepad.

Example 2

C:\PS>stop-process -id 3952 -confirm -passthru

Confirm
Are you sure you want to perform this action?
Performing operation "Stop-Process" on Target "notepad (3952)".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):y
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     41       2      996       3212    31            3952 notepad

Description
-----------
This command stops a particular instance of the Notepad process. It uses the process ID, 3952, to identify the process. The Confirm parameter directs Windows PowerShell to prompt the user before stopping the process. Because the prompt includes the process name, as well as its ID, this is best practice. The PassThru parameter passes the process object to the formatter for display. Without this parameter, there would be no display after a Stop-Process command.

Example 3

C:\PS>calc

c:\PS>$p = get-process calc

c:\PS>stop-process -inputobject $p

c:\PS>get-process | where-object {$_.HasExited}

This series of commands starts and stops the Calc process and then detects processes that have stopped.

The first command ("calc") starts an instance of the calculator. The second command ("$p = get-process calc"), uses the Get-Process cmdlet to get an object representing the Calc process and store it in the $p variable. The third command ("stop-process -inputobject $p") uses the Stop-Process cmdlet to stop the Calc process. It uses the InputObject parameter to pass the object to Stop-Process.

The last command gets all of the processes on the computer that were running but that are now stopped. It uses the Get-Process cmdlet to get all of the processes on the computer. The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects the ones where the value of the HasExited property is TRUE. HasExited is just one property of process objects. To find all the properties, type "get-process | get-member".

Example 4

C:\PS>get-process lsass | stop-process

Stop-Process : Cannot stop process 'lsass (596)' because of the following error: Access is denied
At line:1 char:34
+ get-process lsass  | stop-process <<<<

[ADMIN]: C:\PS> get-process lsass | stop-process
Warning!
Are you sure you want to perform this action?
Performing operation 'Stop-Process' on Target 'lsass(596)'
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

[ADMIN]: C:\PS> get-process lsass | stop-process -force
[ADMIN]: C:\PS>

Description
-----------
These commands show the effect of using the Force parameter to stop a process that is not owned by the user.

The first command uses the Get-Process cmdlet to get the Lsass process. A pipeline operator sends the process to the Stop-Process cmdlet to stop it. As shown in the sample output, the first command fails with an "Access denied" message, because this process can be stopped only by a member of the Administrator's group on the computer.

When Windows PowerShell is opened with the "Run as administrator" option, and the command is repeated, Windows PowerShell prompts you for confirmation.

The second command uses the Force parameter to suppress the prompt. As a result, the process is stopped without confirmation.

See Also

  • Get-Process
  • Start-Process
  • Stop-Process
  • Wait-Process
  • Debug-Process


Stop-Service

Stops one or more running services.

Syntax

Stop-Service [-Name] <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Stop-Service -DisplayName <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Stop-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Stop-Service cmdlet sends a stop message to the Windows Service Controller for each of the specified services. You can specify the services by their service names or display names, or you can use the InputObject parameter to pass a service object representing the services that you want to stop.

Parameters

-DisplayName <string[]>

Specifies the display names of the services to be stopped. Wildcards are permitted.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to stop a service even if that service has dependent services.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Stops only the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ServiceController[]>

Specifies ServiceController objects representing the services to be stopped. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the service names of the services to be stopped. Wildcards are permitted.

The parameter name is optional. You can use "Name" or its alias, "ServiceName", or you can omit the parameter name.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the service. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.ServiceProcess.ServiceController or System.String You can pipe a service object or a string that contains the name of a service to Stop-Service.
Outputs | None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Stop-Service generates a System.ServiceProcess.ServiceController object representing the service. Otherwise, this cmdlet does not generate any output.

Notes

You can also refer to Stop-Service by its built-in alias, "spsv". For more information, see about_Aliases.

Stop-Service can control services only when the current user has permission to do so. If a command does not work correctly, you might not have the required permissions.

To find the service names and display names of the services on your system, type "Get-Service". The service names appear in the Name column and the display names appear in the DisplayName column.

Example 1

C:\PS>stop-service sysmonlog

This command stops the Performance Logs and Alerts (SysmonLog) service on the local computer.

Example 2

C:\PS>get-service -displayname telnet | stop-service

This command stops the Telnet service on the local computer. The command uses the Get-Service cmdlet to get an object representing the Telnet service. The pipeline operator (|) pipes the object to the Stop-Service cmdlet, which stops the service.

Example 3

C:\PS>get-service iisadmin | format-list -property name, dependentservices

C:PS>stop-service iisadmin -force -confirm

The Stop-Service command stops the IISAdmin service on the local computer. Because stopping this service also stops the services that depend on the IISAdmin service, it is best to precede the Stop-Service command with a command that lists the services that depend on the IISAdmin service.

The first command lists the services that depend on IISAdmin. It uses the Get-Service cmdlet to get an object representing the IISAdmin service. The pipeline operator (|) passes the result to the Format-List cmdlet. The command uses the Property parameter of Format-List to list only the Name and DependentServices properties of the service.

The second command stops the IISAdmin service. The Force parameter is required to stop a service that has dependent services. The command uses the Confirm parameter to request confirmation from the user before stopping each service.

See Also

  • Get-Service
  • Suspend-Service
  • Start-Service
  • Restart-Service
  • Resume-Service
  • Set-Service
  • New-Service


Stop-Transcript

Stops a transcript.

Syntax

Stop-Transcript [<CommonParameters>]

Description

The Stop-Transcript cmdlet stops a transcript that was started by using the Start-Transcript cmdlet. You can also stop a transcript by ending the session.

Parameters

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.String Stop-Transcript returns a string that contains a status message and the path to the output file.

Notes

If a transcript has not been started, the command fails.

Example 1

C:\PS>stop-transcript

This command stops any running transcripts.

See Also

  • Start-Transcript


Suspend-Service

Suspends (pauses) one or more running services.

Syntax

Suspend-Service [-Name] <string[]> [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Suspend-Service -DisplayName <string[]> [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Suspend-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Suspend-Service cmdlet sends a suspend message to the Windows Service Controller for each of the specified services. While suspended, the service is still running, but its action is halted until resumed, such as by using Resume-Service. You can specify the services by their service names or display names, or you can use the InputObject parameter to pass a service object representing the services that you want to suspend.

Parameters

-DisplayName <string[]>

Specifies the display names of the services to be suspended. Wildcards are permitted.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Suspends only the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <ServiceController[]>

Specifies ServiceController objects representing the services to be suspended. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the service names of the services to be suspended. Wildcards are permitted.

The parameter name is optional. You can use "Name" or its alias, "ServiceName", or you can omit the parameter name.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PassThru

Returns an object representing the service. By default, this cmdlet does not generate any output.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.ServiceProcess.ServiceController or System.String You can pipe a service object or a string that contains a service name to Suspend-Service.
Outputs | None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Suspend-Service generates a System.ServiceProcess.ServiceController object representing the service. Otherwise, this cmdlet does not generate any output.

Notes

Suspend-Service can control services only when the current user has permission to do so. If a command does not work correctly, you might not have the required permissions.

Also, Suspend-Service can suspend only services that support being suspended and resumed. To determine whether a particular service can be suspended, use the Get-Service cmdlet with the CanPauseAndContinue property. For example, "Get-Service wmi | Format-List name, canpauseandcontinue". To find all services on the computer that can be suspended, type "Get-Service | Where-Object {$_.canpauseandcontinue -eq "True"}".

To find the service names and display names of the services on your system, type "Get-Service". The service names appear in the Name column, and the display names appear in the DisplayName column.

Example 1

C:\PS>suspend-service -displayname "Telnet"

This command suspends the Telnet service (Tlntsvr) service on the local computer.

Example 2

C:\PS>suspend-service -name lanman* -whatif

This command tells what would happen if you suspended the services that have a service name that begins with "lanman". To suspend the services, rerun the command without the WhatIf parameter.

Example 3

C:\PS>get-service schedule | suspend-service

This command uses the Get-Service cmdlet to get an object that represents the Task Scheduler (Schedule) service on the computer. The pipeline operator (|) passes the result to the Suspend-Service cmdlet, which suspends the service.

Example 4

C:\PS>get-service | where-object {$_.canpauseandcontinue -eq "True"} | suspend-service -confirm

This command suspends all of the services on the computer that can be suspended. It uses the Get-Service cmdlet to get objects representing the services on the computer. The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects only the services that have a value of "True" for the CanPauseAndContinue property. Another pipeline operator passes the results to the Suspend-Service cmdlet. The Confirm parameter prompts you for confirmation before suspending each of the services.

See Also

  • Get-Service
  • Start-Service
  • Stop-Service
  • Restart-Service
  • Resume-Service
  • Set-Service
  • New-Service


Tee-Object

Saves command output in a file or variable, and displays it in the console.

Syntax

Tee-Object [-FilePath] <string> [-InputObject <psobject>] [<CommonParameters>]

Tee-Object -Variable <string> [-InputObject <psobject>] [<CommonParameters>]

Description

The Tee-Object cmdlet sends the output of a command in two directions (like the letter "T"). It stores the output in a file or variable and also sends it down the pipeline. If Tee-Object is the last command in the pipeline, the command output is displayed in the console.

Parameters

-FilePath <string>

Specifies the file where the cmdlet stores the object. Accepts wildcards that resolve to a single file.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the object input to the cmdlet. Enter a variable that contains the objects or type a command or expression that gets the objects.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Variable <string>

Assigns a reference to the input objects to the specified variable.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe objects to be redirected to Tee-Object.
Outputs | System.Management.Automation.PSObject Tee-Object returns the object that it redirected.

Notes

You can also use the Out-File cmdlet or the redirection operator, both of which save the output in a file but do not send it down the pipeline.

Tee-Object uses Unicode encoding when it writes to files. As a result, the output might not be formatted properly in files with a different encoding. To specify the encoding, use the Out-File cmdlet.

Example 1

C:\PS>get-process | tee-object -filepath C:\Test1\testfile2.txt

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)    Id ProcessName
-------  ------    -----      ----- -----   ------    -- -----------
   83       4     2300       4520    39     0.30    4032 00THotkey
  272       6     1400       3944    34     0.06    3088 alg
   81       3      804       3284    21     2.45     148 ApntEx
   81       4     2008       5808    38     0.75    3684 Apoint
...

Description
-----------
This command gets a list of the processes running on the computer and sends the result to a file. Because a second path is not specified, the result will be displayed in the console.

Example 2

C:\PS>get-process notepad | tee-object -variable proc | select-object processname,handles

ProcessName                              Handles
-----------                              -------
notepad                                  43
notepad                                  37
notepad                                  38
notepad                                  38

Description
-----------
This command gets a list of the processes running on the computer and sends the result to a variable named "proc". It then pipes the resulting objects along to Select-Object, which selects the ProcessName and Handles property. Note that the $proc variable includes the default information returned by Get-Process.

See Also

  • about_Redirection
  • Select-Object


Test-ComputerSecureChannel

Tests and repairs the secure channel between the local computer and its domain.

Syntax

Test-ComputerSecureChannel [-Repair] [-Server <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Test-ComputerSecureChannel cmdlet verifies that the secure channel between the local computer and its domain is working correctly by checking the status of its trust relationships. If a connection fails, you can use the Repair parameter to try to restore it.

Test-ComputerSecureChannel returns "True" if the secure channel is working correctly and "False" if it is not. This result lets you use the cmdlet in conditional statements in functions and scripts. To get more detailed test results, use the Verbose parameter.

This cmdlet works much like NetDom.exe. Both NetDom and Test-ComputerSecureChannel use the NetLogon service to perform the actions.

Parameters

-Repair

Removes and then rebuilds the secure channel established by the NetLogon service. Use this parameter to try to restore a connection that has failed the test (returned "False".)

To use this parameter, the current user must be a member of the Administrators group on the local computer.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Server <string>

Uses the specified domain controller to run the command. If this parameter is omitted, Test-ComputerSecureChannel selects a default domain controller for the operation.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Boolean The cmdlet returns "True" when the connection is working correctly and "False" when it is not.

Notes

To run a Test-ComputerSecureChannel command on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administrator" option.

Test-ComputerSecureChannel is implemented by using the I_NetLogonControl2 function, which controls various aspects of the Netlogon service.

Example 1

C:\PS>test-computersecurechannel

True

Description
-----------
This command tests the secure channel between the local computer and the domain to which it is joined.

Example 2

C:\PS>test-computersecurechannel -server DCName.fabrikam.com

True

Description
-----------
This command specifies a preferred domain controller for the test.

Example 3

C:\PS>Test-ComputerSecureChannel -repair

True

Description
-----------
This command resets the secure channel between the local computer and its domain.

Example 4

C:\PS>test-computerSecureChannel -verbose

VERBOSE: Performing operation "Test-ComputerSecureChannel" on Target "SERVER01".
True
VERBOSE: "The secure channel between 'SERVER01' and 'net.fabrikam.com' is alive and working correctly."

Description
-----------
This command uses the Verbose common parameter to request detailed messages about the operation. For more information about the Verbose parameter, see about_CommonParameters.

Example 5

C:\PS>set-alias tcsc test-computersecurechannel

if (!(tcsc))
     {write-host "Connection failed. Reconnect and retry."}
else { &(.\get-servers.ps1) }

This example shows how to use Test-ComputerSecureChannel to test a connection before running a script that requires the connection.

The first command uses the Set-Alias cmdlet to create an alias for the cmdlet name. This saves space and prevents typing errors.

The If statement checks the value that Test-ComputerSecureChannel returns before running a script.

See Also

  • Checkpoint-Computer
  • Restart-Computer
  • Stop-Computer
  • Reset-ComputerMachinePassword


Test-Connection

Sends ICMP echo request packets ("pings") to one or more computers.

Syntax

Test-Connection [-ComputerName] <string[]> [[-Source] <string[]>] [-AsJob] [-Authentication {<Default> | <None> | <Connect> | <Call> | <Packet> | <PacketIntegrity> | <PacketPrivacy> | <Unchanged>}] [-BufferSize <int>] [-Count <int>] [-Credential <PSCredential>] [-Delay <int>] [-Impersonation {<Default> | <Anonymous> | <Identify> | <Impersonate> | <Delegate>}] [-Quiet] [-ThrottleLimit <int>] [-TimeToLive <int>] [<CommonParameters>]

Description

The Test-Connection cmdlet sends Internet Control Message Protocol (ICMP) echo request packets ("pings") to one or more remote computers and returns the echo response replies. You can use this cmdlet to determine whether a particular computer can be contacted across an Internet Protocol (IP) network.

You can use the parameters of Test-Connection to specify both the sending and receiving computers, to run the command as a background job, to set a timeout and number of pings, and to configure the connection and authentication.

Unlike the traditional "ping" command, Test-Connection returns a Win32_PingStatus object that you can investigate in Windows PowerShell, but you can use the Quiet parameter to force it to return only a Boolean value.

Parameters

-AsJob

Runs the command as a background job.

Note: To use this parameter, the local and remote computers must be configured for remoting and, on Windows Vista and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option. For more information, see about_Remote_Requirements.

When you use the AsJob parameter, the command immediately returns an object that represents the background job. You can continue to work in the session while the job completes. The job is created on the local computer and the results from remote computers are automatically returned to the local computer. To get the job results, use the Receive-Job cmdlet.

For more information about Windows PowerShell background jobs, see about_Jobs and about_Remote_Jobs.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Authentication <AuthenticationLevel>

Specifies the authentication level that is used for the WMI connection. (Test-Connection uses WMI.)

Valid values are:

Unchanged: The authentication level is the same as the previous command.

Default: Windows Authentication.

None: No COM authentication.

Connect: Connect-level COM authentication.

Call: Call-level COM authentication.

Packet: Packet-level COM authentication.

PacketIntegrity: Packet Integrity-level COM authentication.

PacketPrivacy: Packet Privacy-level COM authentication.

Required? | false
Position? | named
Default Value | 4
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-BufferSize <int>

Specifies the size, in bytes, of the buffer sent with this command. The default value is 32.

Required? | false
Position? | named
Default Value | 32
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string[]>

Specifies the computers to ping. Type the computer names or type IP addresses in IPv4 or IPv6 format. Wildcard characters are not permitted. This parameter is required.

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter even if your computer is not configured to run remote commands.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Count <int>

Specifies the number of echo requests to send. The default value is 4.

Required? | false
Position? | named
Default Value | 4
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one from the Get-Credential cmdlet.

Required? | false
Position? | named
Default Value | Current user
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Delay <int>

Specifies the interval between pings, in seconds.

Required? | false
Position? | named
Default Value | 1 (second)
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Impersonation <ImpersonationLevel>

Specifies the impersonation level to use when calling WMI. (Test-Connection uses WMI.) The default value is "Impersonate".

Valid values are:

Default: Default impersonation.

Anonymous: Hides the identity of the caller.

Identify: Allows objects to query the credentials of the caller.

Impersonate: Allows objects to use the credentials of the caller.

Required? | false
Position? | named
Default Value | 3
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Quiet

Suppresses all errors and returns $True if any pings succeeded and $False if all failed.

Required? | false
Position? | named
Default Value | False
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Source <string[]>

Specifies the names of the computers where the ping originates. Enter a comma-separated list of computer names. The default is the local computer.

Required? | false
Position? | 2
Default Value | Local computer
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ThrottleLimit <int>

Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.

The throttle limit applies only to the current command, not to the session or to the computer.

Required? | false
Position? | named
Default Value | 32
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-TimeToLive <int>

Specifies the maximum time, in seconds, that each echo request packet ("pings") is active. The default value is 80 (seconds). The alias of the TimeToLive parameter is TTL.

Required? | false
Position? | named
Default Value | 80
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs

None

You cannot pipe input to this cmdlet.

Outputs

System.Management.ManagementObject#root\cimv2\Win32_PingStatus, System.Management.Automation.RemotingJob, System.Boolean

When you use the AsJob parameter, the cmdlet returns a job object. When you use the Quiet parameter, it returns a Boolean. Otherwise, this cmdlet returns a Win32_PingStatus object for each ping.

Notes

This cmdlet uses the Win32_PingStatus class. A "get-wmiojbect win32_pingstatus" command is equivalent to a Test-Connection command.

Example 1

C:\PS>test-connection server01

Source        Destination     IPV4Address     IPV6Address  Bytes    Time(ms)
------        -----------     -----------     -----------  -----    --------
ADMIN1        Server01        157.59.137.44                32       0
ADMIN1        Server01        157.59.137.44                32       0
ADMIN1        Server01        157.59.137.44                32       0
ADMIN1        Server01        157.59.137.44                32       1

Description
-----------
This command sends echo request packets ("pings") from the local computer to the Server01 computer. This command uses the ComputerName parameter to specify the Server01 computer, but omits the optional parameter name.

Example 2

C:\PS>test-connection -computername server01, server02, server12 -credential domain01\user01

This command sends pings from the local computer to several remote computers. It uses the Credential parameter to specify a user account that has permission to ping all of the remote computers.

Example 3

C:\PS>test-connection -source Server02, Server 12, localhost -computername Server01

This command sends pings from different source computers to a single remote computer, Server01. Use this command format to test the latency of connections from multiple points.

Example 4

C:\PS>test-connection -computername Server01 -count 3 -delay 2 -TTL 256 -buffersize 256 -throttle 32

This command sends three pings from the local computer to the Server01 computer. It uses the parameters of Test-Connection to customize the command.

Use this command format when the ping response is expected to take longer than usual, either because of an extended number of hops or a high-traffic network condition.

Example 5

C:\PS>$job = test-connection -computername (get-content servers.txt) -asjob

C:\PS> if ($job.jobstateinfo.state -ne "Running") {$results = receive-job $job}

This example shows how to run a Test-Connection command as a Windows PowerShell background job.

The first command uses the Test-Connection cmdlet to ping many computers in an enterprise. The value of ComputerName parameter is a Get-Content command that reads a list of computer names from the Servers.txt file. The command uses the AsJob parameter to run the command as a background job.

The second command checks to see that the job is not still running, and if it is not, it uses a Receive-Job command to get the results and store them in the $results variable.

Example 6

C:\PS>test-connection Server55 -credential domain55\user01 -impersonation Identify

This command uses the Test-Connection cmdlet to ping a remote computer. The command uses the Credential parameter to specify a user account with permission to ping the remote computer and the Impersonation parameter to change the impersonation level to "Identify".

Example 7

C:\PS>if (test-connection -computername Server01 -quiet) {new-pssession Server01}

Description
-----------
This command creates a PSSession on the Server01 only if at least one of the pings sent to the computer succeeds.

The command uses the Test-Connection cmdlet to ping the Server01 computer. The command uses the Quiet parameter, which returns a Boolean value, instead of a Win32_PingStatus object. The value is $True if any of the four pings succeed and is, otherwise, false.

If the Test-Connection command returns a value of $True, the command uses the New-PSSession cmdlet to create the PSSession.

See Also

  • Add-Computer
  • Restart-Computer
  • Stop-Computer


Test-ModuleManifest

Verifies that a module manifest file accurately describes the contents of a module.

Syntax

Test-ModuleManifest [-Path] <string> [<CommonParameters>]

Description

The Test-ModuleManifest cmdlet verifies that the files that are listed in the module manifest (.psd1) file actually exist in the specified paths.

This cmdlet is designed to help module authors test their manifest files. Module users can also use this cmdlet in scripts and commands to detect errors before running scripts that depend on the module.

The Test-ModuleManifest cmdlet returns an object that represents the module (the same type of object that Get-Module returns). If any files are not in the locations specified in the manifest, the cmdlet also generates an error for each missing file.

Parameters

-Path <string>

Specifies the path to the module manifest file. Enter a path (optional) and the name of the module manifest file with the .psd1 file name extension. The default location is the current directory. This parameter is required. The parameter name ("Path") is optional. You can also pipe a path to Test-ModuleManifest.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe the path to a module manifest to Test-ModuleManifest.
Outputs | System.Management.Automation.PSModuleInfo Test-ModuleManifest returns a PSModuleInfo object that represents the module. It returns this object even if the manifest has errors.

Example 1

C:\PS>test-ModuleManifest -path $pshome\Modules\TestModule.psd1

This command tests the TestModule.psd1 module manifest.

Example 2

C:\PS>"$pshome\Modules\TestModule.psd1" | test-modulemanifest

Test-ModuleManifest : The specified type data file 'C:\Windows\System32\Wi
ndowsPowerShell\v1.0\Modules\TestModule\TestTypes.ps1xml' could not be pro
cessed because the file was not found. Please correct the path and try aga
in.
At line:1 char:34
+ "$pshome\Modules\TestModule.psd1" | test-modulemanifest <<<<
    + CategoryInfo          : ResourceUnavailable: (C:\Windows\System32\Win
dowsPowerShell\v1.0\Modules\TestModule\TestTypes.ps1xml:String) [Test-Modul
eManifest], FileNotFoundException
    + FullyQualifiedErrorId : Modules_TypeDataFileNotFound,Microsoft.
PowerShell.Commands.TestModuleManifestCommandName

Name              : TestModule
Path              : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Test
Module\TestModule.psd1
Description       :
Guid              : 6f0f1387-cd25-4902-b7b4-22cff6aefa7b
Version           : 1.0
ModuleBase        : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Test
Module
ModuleType        : Manifest
PrivateData       :
AccessMode        : ReadWrite
ExportedAliases   : {}
ExportedCmdlets   : {}
ExportedFunctions : {}
ExportedVariables : {}
NestedModules     : {}

Description
-----------
This command uses a pipeline operator (|) to send a path string to Test-ModuleManifest.

The command output shows that the test failed, because the TestTypes.ps1xml file, which was listed in the manifest, was not found.

Example 3

C:\PS>function Bool-ModuleManifest ($path)
    {$a = dir $path | test-modulemanifest -erroraction SilentlyContinue; $?}

This function is like Test-ModuleManifest, but it returns a Boolean value;  it returns "True" if the manifest passed the test and "False" otherwise.

The function uses the Get-ChildItem cmdlet (alias = dir) to get the module manifest specified by the $path variable. It uses a pipeline operator (|) to pass the file object to the Test-ModuleManifest cmdlet.

The Test-ModuleManifest command uses the ErrorAction common parameter with a value of SilentlyContinue to suppress the display of any errors that the command generates. It also saves the PSModuleInfo object that Test-ModuleManifest returns in the $a variable, so the object is not displayed.

Then, in a separate command (the semi-colon [;] is the command separator), it displays the value of the $? automatic variable, which returns "True" if the previous command generated no error and "False" otherwise.

You can use this function in conditional statements, such as those that might precede an Import-Module command or a command that uses the module.

See Also

  • Import-Module
  • Get-Module
  • New-Module
  • Remove-Module
  • Export-ModuleMember
  • New-ModuleManifest
  • about_Modules


Test-Path

Determines whether all elements of a path exist.

Syntax

Test-Path [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-IsValid] [-PathType {<Any> | <Container> | <Leaf>}] [-UseTransaction] [<CommonParameters>]

Test-Path [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-IsValid] [-PathType {<Any> | <Container> | <Leaf>}] [-UseTransaction] [<CommonParameters>]

Description

The Test-Path cmdlet determines whether all elements of the path exist. It returns TRUE ($true) if all elements exist and FALSE ($false) if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal (leaf) element.

Parameters

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01". Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Exclude <string[]>

Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Filter <string>

Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Include <string[]>

Tests only the specified paths. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-IsValid

Determines whether the syntax of the path is correct, regardless of whether the elements of the path exist. This parameter returns TRUE if the path syntax is valid and FALSE if it is not.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LiteralPath <string[]>

Specifies a path to be tested. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Path <string[]>

Specifies a path to be tested. Wildcards are permitted. If the path includes spaces, enclose it in quotation marks. The parameter name ("Path") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PathType <TestPathType>

Tells whether the final element in the path is of a particular type. This parameter returns TRUE if the element is of the specified type and FALSE if it is not.

Valid values are:

-- Container: An element that contains other elements, such as a directory or registry key.

-- Leaf: An element that does not contain other elements, such as a file.

-- Any: Either a container or a leaf.Tells whether the final element in the path is of a particular type. Returns TRUE if the element is of the specified type and FALSE if it is not.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a path (but not a literal path) to Test-Path.
Outputs | System.Boolean The cmdlet returns "True" when the path exists and "False" when it does not.

Notes

The cmdlets that contain the Path noun (the Path cmdlets) manipulate path names and return the names in a concise format that all Windows PowerShell providers can interpret. They are designed for use in programs and scripts where you want to display all or part of a path name in a particular format. Use them like you would use Dirname, Normpath, Realpath, Join, or other path manipulators.

You can use the Path cmdlets with several providers, including the FileSystem, Registry, and Certificate providers.

The Test-Path cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers.

Example 1

C:\PS>test-path -path "C:\Documents and Settings\NicoleH"

This command tells whether all elements in the path exist, that is, the C: directory, the Documents and Settings directory, and the NicoleH directory. If any are missing, the cmdlet returns FALSE. Otherwise, it returns TRUE.

Example 2

C:\PS>test-path -path $profile

C:\PS>test-path -path $profile -IsValid

These commands test the path to the Windows PowerShell profile.

The first command determines whether all elements in the path exist. The second command determines whether the syntax of the path is correct. In this case, the path is FALSE, but the syntax is correct (TRUE). These commands use $profile, the automatic variable that points to the location for the profile, even if the profile does not exist.

For more information about automatic variables, see about_Automatic_Variables.

Example 3

C:\PS>test-path -path "C:\CAD\Commercial Buildings\*" -exclude *.dwg

This command tells whether there are any files in the Commercial Buildings directory other than .dwg files.

The command uses the Path parameter to specify the path. Because it includes a space, the path is enclosed in quotes. The asterisk at the end of the path indicates the contents of the Commercial Building directory. (With long paths, like this one, type the first few letters of the path, and then use the TAB key to complete the path.)

The command uses the Exclude parameter to specify files that will be omitted from the evaluation.

In this case, because the directory contains only .dwg files, the result is FALSE.

Example 4

C:\PS>test-path -path $profile -pathtype leaf

This command tells whether the path stored in the $profile variable leads to a file. In this case, because the Windows PowerShell profile is a .ps1 file, the cmdlet returns TRUE.

Example 5

C:\PS>test-path -path HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell

TRUE

C:\PS> test-path -path HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\ExecutionPolicy
FALSE

Description
-----------
These commands use the Test-Path cmdlet with the Windows PowerShell registry provider.

The first command tests whether the registry path to the Microsoft.PowerShell registry key is correct on the system. If Windows PowerShell is installed correctly, the cmdlet returns TRUE.

Test-Path does not work correctly with all Windows PowerShell providers. For example, you can use Test-Path to test the path to a registry key, but if you use it to test the path to a registry entry, it always returns FALSE, even if the registry entry is present.

See Also

  • about_Providers
  • Convert-Path
  • Split-Path
  • Resolve-Path
  • Join-Path


Test-WSMan

Tests whether the WinRM service is running on a local or remote computer.

Syntax

Test-WSMan [[-ComputerName] <string>] [-Authentication <Authentication>] [-Credential <PSCredential>] [<CommonParameters>]

Description

The Test-WSMan cmdlet submits an identification request that determines whether the WinRM service is running on a local or remote computer. If the tested computer is running the service, the cmdlet displays the WS-Management identity schema, the protocol version, the product vendor, and the product version of the tested service.

Parameters

-Authentication <Authentication>

Specifies the authentication mechanism to be used at the server. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.

- Default : Use the authentication method implemented by the WS-Management protocol.

- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.

- Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates.

- Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.

- CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

Caution: CredSSP delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

Important: If the authentication parameter is not specified, then the Test-WSMan request will be sent to the remote machine anonymously (without using authentication). If the Test-WSMan request is made anonymously, it does not return any information that is specific to the operating-system version. Instead, Test-WSMan displays null values for the operating system version and service pack level (OS: 0.0.0 SP: 0.0).

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used.

Required? | false
Position? | 1
Default Value | localhost
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Credential <PSCredential>

Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or User@Domain.com. Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None This cmdlet does not accept any input.
Outputs | None This cmdlet does not generate any output object.

Notes

By default, the Test-WSMan cmdlet queries the WinRM service without using authentication, and it does not return any information that is specific to the operating-system version. Instead, it displays null values for the operating system version and service pack level (OS: 0.0.0 SP: 0.0).

Example 1

C:\PS>test-wsman

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 0.0.0 SP: 0.0 Stack: 2.0

Description
-----------
This command determines whether the WinRM service is running on the local computer or on a remote computer.

Example 2

C:\PS>test-wsman -computername server01

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 0.0.0 SP: 0.0 Stack: 2.0

Description
-----------
This command determines whether the WinRM service is running on the server01 computer named.

Example 3

C:\PS>test-wsman -authentication default

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 6.0.6001 SP: 1.0 Stack: 2.0

Description
-----------
This command tests to see if the WS-Management (WinRM) service is running on the local computer using the authentication parameter.

Using the authentication parameter allows the Test-WSMan cmdlet to return the Operating System version.

Example 4

C:\PS>test-wsman -computername server01 -authentication default

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 6.1.7021 SP: 0.0 Stack: 2.0

Description
-----------
This command tests to see if the WS-Management (WinRM) service is running on the computer named server01 using the authentication parameter.

Using the authentication parameter allows the Test-WSMan cmdlet to return the operating system version.

See Also

  • Connect-WSMan
  • Disable-WSManCredSSP
  • Disconnect-WSMan
  • Enable-WSManCredSSP
  • Get-WSManCredSSP
  • Get-WSManInstance
  • Invoke-WSManAction
  • New-WSManInstance
  • New-WSManSessionOption
  • Remove-WSManInstance
  • Set-WSManInstance
  • Set-WSManQuickConfig


Trace-Command

Configures and starts a trace of the specified expression or command.

Syntax

Trace-Command [-Command] <string> [-ArgumentList <Object[]>] [-Name] <string[]> [[-Option] {<None> | <Constructor> | <Dispose> | <Finalizer> | <Method> | <Property> | <Delegates> | <Events> | <Exception> | <Lock> | <Error> | <Errors> | <Warning> | <Verbose> | <WriteLine> | <Data> | <Scope> | <ExecutionFlow> | <Assert> | <All>}] [-Debugger] [-FilePath <string>] [-Force] [-InputObject <psobject>] [-ListenerOption {<None> | <LogicalOperationStack> | <DateTime> | <Timestamp> | <ProcessId> | <ThreadId> | <Callstack>}] [-PSHost] [<CommonParameters>]

Trace-Command [-Expression] <scriptblock> [-Name] <string[]> [[-Option] {<None> | <Constructor> | <Dispose> | <Finalizer> | <Method> | <Property> | <Delegates> | <Events> | <Exception> | <Lock> | <Error> | <Errors> | <Warning> | <Verbose> | <WriteLine> | <Data> | <Scope> | <ExecutionFlow> | <Assert> | <All>}] [-Debugger] [-FilePath <string>] [-Force] [-InputObject <psobject>] [-ListenerOption {<None> | <LogicalOperationStack> | <DateTime> | <Timestamp> | <ProcessId> | <ThreadId> | <Callstack>}] [-PSHost] [<CommonParameters>]

Description

The Trace-Command cmdlet configures and starts a trace of the specified expression or command. It works like Set-TraceSource, except that it applies only to the specified command.

Parameters

-ArgumentList <Object[]>

Specifies the parameters and parameter values for the command being traced. The alias for ArgumentList is Args. This feature is especially useful for debugging dynamic parameters.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Command <string>

Specifies a command that is being processed during the trace.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Debugger

Sends the trace output to the debugger. You can view the output in any user-mode or kernel mode debugger or in Visual Studio. This parameter also selects the default trace listener.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Expression <scriptblock>

Specifies the expression that is being processed during the trace. Enclose the expression in curly braces ({}).

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-FilePath <string>

Sends the trace output to the specified file. This parameter also selects the file trace listener.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Force

Allows the cmdlet to append trace information to a read-only file. Used with the FilePath parameter. Even using the Force parameter, the cmdlet cannot override security restrictions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Provides input to the expression that is being processed during the trace.

You can enter a variable that represents the input that the expression accepts, or pass an object through the pipeline.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-ListenerOption <TraceOptions>

Adds optional data to the prefix of each trace message in the output. The valid values are None, LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, and Callstack. "None" is the default.

To specify multiple options, separate them with commas, but with no spaces, and enclose them in quotation marks, such as "ProcessID,ThreadID".

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string[]>

Determines which Windows PowerShell components are traced. Enter the name of the trace source of each component. Wildcards are permitted. To find the trace sources on your computer, type "Get-TraceSource".

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Option <PSTraceSourceOptions>

Determines the type of events that are traced.

The valid values are None, Constructor, Dispose, Finalizer, Method, Property, Delegates, Events, Exception, Lock, Error, Errors, Warning, Verbose, WriteLine, Data, Scope, ExecutionFlow, Assert, and All. "All" is the default.

The following values are combinations of other values:

-- ExecutionFlow: (Constructor, Dispose, Finalizer, Method, Delegates, Events, and Scope)

-- Data: (Constructor, Dispose, Finalizer, Property, Verbose, and WriteLine)

-- Errors: (Error and Exception).

To specify multiple options, separate them with commas, but with no spaces, and enclose them in quotation marks, such as "Constructor,Dispose".

Required? | false
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PSHost

Sends the trace output to the Windows PowerShell host. This parameter also selects the PSHost trace listener.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe objects that represent input to the expression to Trace-Command.
Outputs | System.Management.Automation.PSObject Returns the command trace in the debug stream.

Notes

Tracing is a method that developers use to debug and refine programs. When tracing, the program generates detailed messages about each step in its internal processing.

The Windows PowerShell tracing cmdlets are designed to help Windows PowerShell developers, but they are available to all users. They let you monitor nearly every aspect of the functionality of the shell.

To find the Windows PowerShell components that are enabled for tracing, type "Get-Help Get-TraceSource."

A "trace source" is the part of each Windows PowerShell component that manages tracing and generates trace messages for the component. To trace a component, you identify its trace source.

A "trace listener" receives the output of the trace and displays it to the user. You can elect to send the trace data to a user-mode or kernel-mode debugger, to the host or console, to a file, or to a custom listener derived from the System.Diagnostics.TraceListener class.

When you use the Command parameter set, Windows PowerShell processes the command just as it would be processed in a pipeline. For example, command discovery is not repeated for each incoming object.

The names of the Name, Expression, Option, and Command parameters are optional. If you omit the parameter names, the unnamed parameter values must appear in this order: Name, Expression, Option or Name, Command,-Option . If you include the parameter names, the parameters can appear in any order.

Example 1

C:\PS>trace-command -name metadata,parameterbinding,cmdlet -expression {get-process notepad} -pshost

This command starts a trace of metadata processing, parameter binding, and cmdlet creation and destruction of the "get-process notepad" expression. It uses the Name parameter to specify the trace sources, the Expression parameter to specify the command, and the PSHost parameter to send the output to the console. Because it does not specify any tracing options or listener options, the command uses the defaults, "All" for the tracing options, and "None" for the listener options.

Example 2

C:\PS>trace-command -name commandprocessor,pipelineprocessor -command get-alias -argumentlist "ghy" -option executionflow -listenerOption "timestamp,callstack" -filepath c:\test\debug.txt

This command starts a trace of the command processor and pipeline processor while processing the "get-alias cd" command.

It uses the Name parameter to specify the trace sources, the Command parameter to specify the command, the ArgumentList parameter to specify the parameters of the Get-Alias command, the Option parameter to specify tracing options, and the ListenerOption parameter to specify the fields in the trace message prefix. The FilePath parameter sends the output to the C:\Test\Debug.txt file.

Example 3

C:\PS>$a = "i*"

C:\PS> trace-command parameterbinding {get-alias $input} -pshost -inputobject $a

These commands trace the actions of the ParameterBinding operations of Windows PowerShell while it processes a Get-Alias expression that takes input from the pipeline.

In Trace-Command, the InputObject parameter passes an object to the expression that is being processed during the trace.

The first command stores the string "i*" in the $a variable. The second command uses the Trace-Command cmdlet with the ParameterBinding trace source. The PSHost parameter sends the output to the console.

The expression being processed is "get-alias $input", where the $input variable is associated with the InputObject parameter. The InputObject parameter passes the variable $a to the expression. In effect, the command being processed during the trace is "get-alias -inputobject $a" or "$a | get-alias".

See Also

  • Get-TraceSource
  • Set-TraceSource


Undo-Transaction

Rolls back the active transaction.

Syntax

Undo-Transaction [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Undo-Transaction cmdlet rolls back the active transaction. When you roll back a transaction, the changes made by the commands in the transaction are discarded and the data is restored to its original form.

If the transaction includes multiple subscribers, an Undo-Transaction command rolls back the entire transaction for all subscribers.

By default, transactions are rolled back automatically if any command in the transaction generates an error. However, transactions can be started with a different rollback preference and you can use this cmdlet to roll back the active transaction at any time.

The Undo-Transaction cmdlet is one of a set of cmdlets that support the transactions feature in Windows PowerShell. For more information, see about_Transactions.

Parameters

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None This cmdlet does not return any output.

Notes

You cannot roll back a transaction that has been committed.

You cannot roll back any transaction other than the active transaction. To roll back a different, independent transaction, you must first commit or roll back the active transaction.

Rolling back the transaction ends the transaction. To use a transaction again, you must start a new transaction.

Example 1

C:\PS>undo-transaction

This command rolls back the current (active) transaction.

Example 2

C:\PS>cd hkcu:\software

PS HKCU:\Software> start-transaction
PS HKCU:\Software> new-item MyCompany -usetransaction
PS HKCU:\Software> undo-transaction

Description
-----------
This command starts a transaction and then rolls it back. As a result, no changes are made to the registry.

Example 3

C:\PS>cd hkcu:\software

PS HKCU:\Software> start-transaction
PS HKCU:\Software> new-item MyCompany -usetransaction
PS HKCU:\Software> get-transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   -----
Error                1                 Active

PS HKCU:\Software> start-transaction
PS HKCU:\Software> get-transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   -----
Error                2                 Active

PS HKCU:\Software> undo-transaction
PS HKCU:\Software> get-transaction

RollbackPreference   SubscriberCount   Status
------------------   ---------------   -----
Error                0                 RolledBack

Description
-----------
This example demonstrates that when any subscriber rolls back a transaction, the entire transaction is rolled back for all subscribers.

The first command changes the location to the HKCU:\Software registry key.

The second command starts a transaction.

The third command uses the New-Item cmdlet to create a new registry key. The command uses the UseTransaction parameter to include the change in the transaction.

The fourth command uses the Get-Transaction cmdlet to get the active transaction. Notice that the status is Active and the subscriber count is 1.

The fifth command uses the Start-Transaction command again. Typically,
starting a transaction while another transaction is in progress occurs when a script used by the main transaction includes its own complete transaction. (This example is done interactively so that you can examine it in stages.)

When you enter a Start-Transaction command while another transaction is in progress, the commands join the existing transaction as a new "subscriber" and the subscriber count is incremented.

The sixth command uses the Get-Transaction cmdlet to get the active transaction. Notice that the subscriber count is now 2.

The seventh command uses the Undo-Transaction cmdlet to roll back the transaction. This command does not return any objects.

The final command is a Get-Transaction command that gets the active (or in this case, the most recently active) transaction. The results show that the transaction is rolled back, and that the subscriber count is 0, showing that the transaction was rolled back for all subscribers.

See Also

  • about_Transactions
  • about_Providers
  • Start-Transaction
  • Get-Transaction
  • Complete-Transaction
  • Use-Transaction


Unregister-Event

Cancels an event subscription.

Syntax

Unregister-Event [-SubscriptionId] <int> [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Unregister-Event [-SourceIdentifier] <string> [-Force] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Unregister-Event cmdlet cancels an event subscription that was created by using the Register-EngineEvent, Register-ObjectEvent, or Register-WmiEvent cmdlet.

When an event subscription is canceled, the event subscriber is deleted from the session and the subscribed events are no longer added to the event queue. When you cancel a subscription to an event created by using the New-Event cmdlet, the new event is also deleted from the session.

Unregister-Event does not delete events from the event queue. To delete events, use the Remove-Event cmdlet.

Parameters

-Force

Cancels all event subscriptions, including subscriptions that were hidden by using the SupportEvent parameter of Register-ObjectEvent, Register-WmiEvent, and Register-EngineEvent.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SourceIdentifier <string>

Cancels event subscriptions that have the specified source identifier.

A SourceIdentifier or SubscriptionId parameter must be included in every command.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-SubscriptionId <int>

Cancels event subscriptions that have the specified subscription identifier.

A SourceIdentifier or SubscriptionId parameter must be included in every command.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSEventSubscriber You can pipe the output from Get-EventSubscriber to Unregister-Event.
Outputs | None This cmdlet does not return any output.

Notes

Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

Unregister-Event cannot delete events created by using the New-Event cmdlet unless you have subscribed to the event by using the Register-EngineEvent cmdlet. To delete a custom event from the session, you must remove it programmatically or close the session.

Example 1

C:\PS>unregister-event -sourceIdentifier ProcessStarted

This command cancels the event subscription that has a source identifier of "ProcessStarted".

To find the source identifier of an event, use the Get-Event cmdlet. To find the source identifier of an event subscription, use the Get-EventSubscriber cmdlet.

Example 2

C:\PS>unregister-event -subscriptionId 2

This command cancels the event subscription that has a subscription identifier of 2.

To find the subscription identifier of an event subscription, use the Get-EventSubscriber cmdlet.

Example 3

C:\PS>get-eventsubscriber -force | unregister-event -force

This command cancels all event subscriptions in the session.

The command uses the Get-EventSubscriber cmdlet to get all event subscriber objects in the session, including the subscribers that are hidden by using the SupportEvent parameter of the event registration cmdlets.

It uses a pipeline operator (|) to send the subscriber objects to Unregister-Event, which deletes them from the session. To complete the task, the Force parameter is also required on Unregister-Event.

See Also

  • Register-ObjectEvent
  • Register-EngineEvent
  • Register-WmiEvent
  • Unregister-Event
  • Get-Event
  • New-Event
  • Remove-Event
  • Wait-Event
  • Get-EventSubscriber


Unregister-PSSessionConfiguration

Deletes registered session configurations from the computer.

Syntax

Unregister-PSSessionConfiguration [-Name] <string> [-Force] [-NoServiceRestart] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Unregister-PSSessionConfiguration cmdlet deletes registered session configurations from the computer. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users.

If you accidentally delete the default Microsoft.PowerShell or Microsoft.PowerShell32 session configurations, use the Enable-PSRemoting cmdlet to restore them.

Parameters

-Force

Suppresses all user prompts, and restarts the WinRM service without prompting. Restarting the service makes the configuration change effective.

To prevent a restart and suppress the restart prompt, use the NoServiceRestart parameter.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Name <string>

Specifies the names of session configurations to delete. Enter one or more configuration names. Wildcards are permitted. This parameter is required.

You can also pipe a session configuration object to Unregister-PSSessionConfiguration.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-NoServiceRestart

Does not restart the WinRM service, and suppresses the prompt to restart the service.

By default, when you enter an Unregister-PSSessionConfiguration command, you are prompted to restart the WinRM service to make the change effective. Until the WinRM service is restarted, users can still use the unregistered session configuration, even though Get-PSSessionConfiguration does not find it.

To restart the WinRM service without prompting, use the Force parameter. To restart the WinRM service manually, use the Restart-Service cmdlet.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration You can pipe a session configuration object from Get-PSSessionConfiguration to Unregister-PSSessionConfiguration.
Outputs | None This cmdlet does not return any objects.

Notes

To run this cmdlet on Windows Vista, Windows Server 2008, and later versions of Windows, you must start Windows PowerShell with the "Run as administrator" option.

Example 1

C:\PS>unregister-pssessionconfiguration -name MaintenanceShell

This command deletes the MaintenanceShell session configuration from the computer.

Example 2

C:\PS>unregister-pssessionconfiguration -maintenanceShell -force

This command deletes the MaintenanceShell session configuration from the computer. The command uses the Force parameter to suppress all user messages and to restart the WinRM service without prompting.

Example 3

C:\PS>unregister-pssessionconfiguration -name *

C:\PS> get-pssessionconfiguration -name * | unregister-pssessionconfiguration

Description
-----------
These commands delete all of the session configurations on the computer. The commands have the same effect and can be used interchangeably.

Example 4

C:\PS>unregister-pssessionconfiguration -name maintenanceShell -noServiceRestart

C:\PS> get-pssessionconfiguration -name maintenanceShell

Get-PSSessionConfiguration -name maintenanceShell : No Session Configuration matches criteria "maintenanceShell".
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

C:\PS> new-pssession -configurationName MaintenanceShell

 Id Name      ComputerName    State    Configuration         Availability
 -- ----      ------------    -----    -------------         ------------
  1 Session1  localhost       Opened   MaintenanceShell      Available

C:\PS> restart-service winrm

C:\PS> new-pssession -configurationName MaintenanceShell
[localhost] Connecting to remote server failed with the following error message : The WS-Management service cannot process the request. The resource
URI (http://schemas.microsoft.com/powershell/MaintenanceShell) was not found in the WS-Management catalog. The catalog contains the metadata that describes resour
ces, or logical endpoints. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionOpenFailed

Description
-----------
This example shows the effect of using the NoServiceRestart parameter of Unregister-PSSessionConfiguration. This parameter is designed to prevent a service restart, which would disrupt any sessions on the computer.

The first command uses the Unregister-PSSessionConfiguration cmdlet to deletes the MaintenanceShell session configuration. However, because the command uses the NoServiceRestart parameter, the WinRM service is not restarted and the change is not yet completely effective.

The second command uses the Get-PSSessionConfiguration cmdlet to get the MaintenanceShell session. Because the session has been removed from the WS-Management resource table, Get-PSSession cannot return it.

The third command uses the New-PSSession cmdlet to create a session on the local computer that uses the MaintenanceShell configuration. The command succeeds.

The fourth command uses the Restart-Service cmdlet to restart the WinRM service.

The fifth command again uses the New-PSSession cmdlet to create a session that uses the MaintenanceShell configuration. This time, the session fails because the MaintenanceShell configuration has been deleted.

See Also

  • about_Session_Configurations
  • Disable-PSSessionConfiguration
  • Enable-PSSessionConfiguration
  • Get-PSSessionConfiguration
  • Register-PSSessionConfiguration
  • Set-PSSessionConfiguration
  • WS-Management Provider


Update-FormatData

Updates the formatting data in the current session.

Syntax

Update-FormatData [[-AppendPath] <string[]>] [-PrependPath <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Update-FormatData cmdlet reloads the formatting data from formatting files into the current session. This cmdlet lets you update the formatting data without restarting Windows PowerShell.

Without parameters, Update-FormatData reloads the formatting files that it loaded previously. You can use the parameters of Update-FormatData to add new formatting files to the session.

Formatting files are text files in XML format with the format.ps1xml file name extension. The formatting data in the files defines the display of Microsoft .NET Framework objects in the session.

When Windows PowerShell starts, it loads the format data from the formatting files in the Windows PowerShell installation directory ($pshome) into the session. You can use Update-FormatData to reload the formatting data into the current session without restarting Windows PowerShell. This is useful when you have added or changed a formatting file, but do not want to interrupt the session.

For more information about formatting files in Windows PowerShell, see about_Format.ps1xml.

Parameters

-AppendPath <string[]>

Adds the specified formatting files to the session. The files are loaded after Windows PowerShell loads the built-in formatting files.

When formatting .NET objects, Windows PowerShell uses the first formatting definition that it finds for each .NET type. If you use the AppendPath parameter, Windows PowerShell searches the data from the built-in files before it encounters the formatting data that you are adding.

Use this parameter to add a file that formats a .NET object that is not referenced in the built-in formatting files.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PrependPath <string[]>

Adds the specified formatting files to the session. The files are loaded before Windows PowerShell loads the built-in formatting files.

When formatting .NET objects, Windows PowerShell uses the first formatting definition that it finds for each .NET type. If you use the PrependPath parameter, Windows PowerShell searches the data from the files that you are adding before it encounters the formatting data from the built-in files.

Use this parameter to add a file that formats a .NET object that is also referenced in the built-in formatting files.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains the append path to Update-FormatData.
Outputs | None The cmdlet does not return any output.

Notes

Update-FormatData also updates the formatting data for commands in the session that were imported from modules. If the formatting file for a module changes, you can run an Update-FormatData command to update the formatting data for imported commands. You do not need to import the module again.

Example 1

C:\PS>update-formatdata

This command reloads the formatting files that it loaded previously.

Example 2

C:\PS>update-formatdata -appendpath trace.format.ps1xml, log.format.ps1xml

This command reloads the formatting files into the session, including two new files, Trace.format.ps1xml and Log.format.ps1xml.

Because the command uses the AppendPath parameter, the formatting data in the new files is loaded after the formatting data from the built-in files.

The AppendPath parameter is used because the new files contain formatting data for objects that are not referenced in the built-in files.

Example 3

C:\PS>update-formatdata -prependPath c:\test\NewFiles.format.ps1xml

# Edit the NewFiles.format.ps1 file.

C:\PS> update-formatdata

Description
-----------
This example shows how to reload a formatting file after you have edited it.

The first command adds the NewFiles.format.ps1xml file to the session. It uses the PrependPath parameter because the file contains formatting data for objects that are referenced in the built-in files.

After adding the NewFiles.format.ps1xml file and testing it in these session, the author edits the file.

The second command uses the Update-FormatData cmdlet to reload the formatting files. Because the NewFiles.format.ps1xml file was previously loaded, Update-FormatData automatically reloads it without using parameters.


Update-List

Adds items to and removes items from a property value that contains a collection of objects.

Syntax

Update-List [-Add <Object[]>] [-Remove <Object[]>] [[-Property] <string>] [-InputObject <psobject>] [<CommonParameters>]

Update-List -Replace <Object[]> [[-Property] <string>] [-InputObject <psobject>] [<CommonParameters>]

Description

The Update-List cmdlet adds items to and removes items from a property value of an object, and then it returns the updated object. This cmdlet is designed for properties that contain collections of objects.

The Add and Remove parameters add individual items to and remove them from the collection. The Replace parameter replaces the entire collection.

If you do not specify a property in the command, Update-List returns an object that describes the update instead of updating the object. You can submit the update object to cmdlets that change objects, such as Set-* cmdlets.

This cmdlet works only when the property that is being updated supports the IList interface that Update-List uses. Also, any Set-* cmdlets that accept an update must support the IList interface. The core cmdlets that are installed with Windows PowerShell do not support this interface. To determine whether a cmdlet supports Update-List, see the cmdlet Help topic.

Parameters

-Add <Object[]>

Specifies the property values to be added to the collection. Enter the values in the order that they should appear in the collection.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be updated. You can also pipe the object to be updated to Update-List.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Property <string>

Identifies the property that contains the collection that is being updated. If you omit this parameter, Update-List returns an object that represents the change instead of changing the object.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Remove <Object[]>

Specifies the property values to be removed from the collection.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Replace <Object[]>

Specifies a new collection. This parameter replaces all items in the original collection with the items specified by this parameter.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe the objects to be updated to Update-List.
Outputs | Objects or System.Management.Automation.PSListModifier Update-List returns the updated object, or it returns an object that represents the update action.

Example 1

C:\PS>get-mailbox | update-list -Property aliases -Add "A","B" -Remove "X","Y" | set-mailbox

This command adds A and B and removes X and Y from the Aliases property of a mailbox.

The command uses the Get-MailBox cmdlet from Microsoft Exchange Server to get the mailbox. A pipeline operator sends the mailbox object to the Update-List cmdlet.

The Update-List command uses the Property parameter to indicate that the Aliases property of the mailbox is being updated, and it uses the Add and Remove parameters to specify the items that are being added and removed from the collection. The Aliases property fulfills the conditions of Update-List, because it stores a collection of Microsoft .NET Framework objects that have Add and Remove methods.

The Update-List cmdlet returns the updated mailbox, which is piped to the Set-MailBox cmdlet, which changes the mailbox.

For more information about Get-Mailbox, see http://go.microsoft.com/fwlink/?LinkId=111536.

Example 2

C:\PS>$m = get-mailbox

C:\PS> update-list -InputObject $m -Property aliases -Add "A","B" -Remove "X", "Y" | set-mailbox

This command adds A and B to the value of the Aliases property of a mailbox and removes X and Y. This command has the same effect as the previous command, although it has a slightly different format.

The command uses the Get-MailBox cmdlet to get the mailbox, and it saves the mailbox in the $m variable. This command uses the InputObject parameter of Update-List to specify the mailbox. The value of InputObject is the mailbox in the $m variable. It uses the Property parameter to specify the Aliases property and the Add and Remove parameters to specify the items being added to and removed from the value of Aliases.

The command uses a pipeline operator (|) to send the updated mailbox object to the Set-Mailbox cmdlet, which changes the mailbox.

Example 3

C:\PS>get-mailbox | set-mailbox -alias (update-list -Add "A", "B" -Remove "X","Y")

This command adds A and B to the value of the Aliases property of a mailbox and removes X and Y. This command has the same effect as the two previous commands, but it uses a different procedure to perform the task.

Instead of updating the Aliases property of the mailbox before sending it to Set-Mailbox, this command uses Update-List to create an object that represents the change. Then it submits the change to the Alias parameter of Set-Mailbox.

The command uses the Get-MailBox cmdlet to get the mailbox. A pipeline operator sends the mailbox object to the Set-Mailbox cmdlet, which changes mailboxes.

The command uses the Alias parameter of Set-Mailbox to change the Aliases property of the mailbox object. The value of the Alias parameter is an Update-List command that creates an object that represents the update. The Update-List command is enclosed in parentheses to ensure that it runs before the value of the Alias parameter is evaluated. When the Set-Mailbox command completes, the mailbox is changed.

Example 4

C:\PS>update-list -InputObject $a -Property aliases -replace "A", "B" | set-mailbox

This command uses the Replace operator of Update-List to replace the collection in the Aliases property of the object in $a with a new collection.

This command uses the InputObject parameter which, in this case, is equivalent to using a pipeline operator to pass $a to Update-List.

See Also

  • Select-Object


Update-TypeData

Updates the current extended type configuration by reloading the *.types.ps1xml files into memory.

Syntax

Update-TypeData [[-AppendPath] <string[]>] [-PrependPath <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]

Description

The Update-TypeData cmdlet updates the current extended type configuration by reloading the *.types.ps1xml files into memory. Extended type information is normally loaded when Windows PowerShell requires the type information it contains. The Update-TypeData cmdlet can be used to preload all type information. It is particularly useful when you are developing types and want to load those new types for testing purposes.

For more information about the *types.ps1xml files in Windows PowerShell, see about_Types.ps1xml.

Parameters

-AppendPath <string[]>

Specifies the path to the optional .ps1xml files that will be included in the list of files loaded. These are processed after the built-in files are loaded.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-PrependPath <string[]>

Specifies the path to the optional .ps1xml files that will be included in the list of files loaded. However, these files are processed in the order they are specified and before the built-in files are loaded.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Confirm

Prompts you for confirmation before executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-WhatIf

Describes what would happen if you executed the command without actually executing the command.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains the append path to Update-TypeData.
Outputs | None This cmdlet does not return any output.

Example 1

C:\PS>update-typedata

This example updates the extended type configuration from the *.types.ps1xml files.

Example 2

C:\PS>update-typedata -prependpath typesA.types.Ps1xml, typesB.types.Ps1xml

This example updates the extended type configuration from the *.types.ps1xml files, processing the typesA and typesB files first.


Use-Transaction

Adds the script block to the active transaction.

Syntax

Use-Transaction [-TransactedScript] <scriptblock> [-UseTransaction] [<CommonParameters>]

Description

The Use-Transaction cmdlet adds a script block to an active transaction. This enables you to do transacted scripting using transaction-enabled Microsoft .NET Framework objects. The script block can contain only transaction-enabled .NET Framework objects, such as instances of the Microsoft.PowerShell.Commands.Management.TransactedString class.

The UseTransaction parameter, which is optional for most cmdlets, is required when using this cmdlet.

The Use-Transaction cmdlet is one of a set of cmdlets that support the transactions feature in Windows PowerShell. For more information, see about_Transactions.

Parameters

-TransactedScript <scriptblock>

Specifies the script block that is run in the transaction. Enter any valid script block enclosed in braces ( { } ). This parameter is required.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-UseTransaction

Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | PSObject Use-Transaction returns the result of the transaction.

Notes

The Use-Transaction parameter includes the command in the active transaction. Because the Use-Transaction cmdlet is always used in transactions, this parameter is required to make any Use-Transaction command effective.

Example 1

C:\PS>start-transaction

C:\PS> $transactedString = New-Object Microsoft.PowerShell.Commands.Management.TransactedString

C:\PS> $transactedString.Append("Hello")
C:\PS> use-transaction -TransactedScript { $transactedString.Append(", World") } -UseTransaction

C:\PS> $transactedString.ToString()
Hello

C:\PS> use-transaction -transactedScript { $transactedString.ToString() } -UseTransaction
Hello, World

C:\PS> complete-transaction
C:\PS> $transactedString.ToString()
Hello, World

Description
-----------
This example shows how to use the Use-Transaction cmdlet to script against a transaction-enabled .NET Framework object. In this case, the object is a TransactedString object.

The first command uses the Start-Transaction cmdlet to start a transaction.

The second command uses the New-Object command to create a TransactedString object. It stores the object in the $TransactedString variable.

The third and fourth commands both use the Append method of the TransactedString object to add text to the value of $TransactedString. One command is part of the transaction; the other is not.

The third command uses the Append method of the transacted string to add "Hello" to the value of $TransactedString. Because the command is not part of the transaction, the change is applied immediately.

The fourth command uses the Use-Transaction cmdlet to add text to the string within the transaction. The command uses the Append method to add ", World" to the value of $TransactedString. The command is enclosed in braces ( {} ) to make it a script block. The UseTransaction parameter is required in this command.

The fifth and sixth commands use the ToString method of the TransactedString object to display the value of the TransactedString as a string. Again, one command is part of the transaction; the other is not.

The fifth command uses the ToString method to display the current value of the $TransactedString variable. Because it is not part of the transaction, it displays only the current state of the string.

The sixth command uses the Use-Transaction cmdlet to run the same command within the transaction. Because the command is part of the transaction, it displays the current value of the string within the transaction, much like a preview of the transaction changes.

The seventh command uses the Complete-Transaction cmdlet to commit the transaction.

The final command uses the ToString method to display the resulting value of the variable as a string.

Example 2

C:\PS>start-transaction

C:\PS> $transactedString = New-Object Microsoft.PowerShell.Commands.Management.TransactedString

C:\PS> $transactedString.Append("Hello")
C:\PS> use-transaction -TransactedScript { $transactedString.Append(", World") } -UseTransaction

C:\PS> undo-transaction

C:\PS> $transactedString.ToString()
Hello

Description
-----------
This example shows the effect of rolling back a transaction that includes Use-Transaction commands. Like all commands in a transaction, when the transaction is rolled back, the transacted changes are discarded and the data is unchanged.

The first command uses the Start-Transaction cmdlet to start a transaction.

The second command uses the New-Object command to create a TransactedString object. It stores the object in the $TransactedString variable.

The third command, which is not part of the transaction, uses the Append method to add "Hello" to the value of $TransactedString.

The fourth command uses the Use-Transaction cmdlet to run another command that uses the Append method within the transaction. The command uses the Append method to add ", World" to the value of $TransactedString.

The fifth command uses the Undo-Transaction cmdlet to roll back the transaction. As a result, all commands performed within the transaction are reversed.

The final command uses the ToString method to display the resulting value of $TransactedString as a string. The results show that only the changes made outside of the transaction were applied to the object.

See Also

  • about_Transactions
  • Start-Transaction
  • Get-Transaction
  • Complete-Transaction
  • Undo-Transaction


Wait-Event

Waits until a particular event is raised before continuing to run.

Syntax

Wait-Event [[-SourceIdentifier] <string>] [-Timeout <int>] [<CommonParameters>]

Description

The Wait-Event cmdlet suspends execution of a script or function until a particular event is raised. Execution resumes when the event is detected. To cancel the wait, press CTRL+C.

This feature provides an alternative to polling for an event. It also allows you to determine the response to an event in two different ways: by using the Action parameter of the event subscription and by waiting for an event to return and then respond with an action.

Parameters

-SourceIdentifier <string>

Waits only for events with the specified source identifier. By default, Wait-Events waits for any event.

Required? | false
Position? | 1
Default Value | All events
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Timeout <int>

Determines the maximum time, in seconds, that Wait-Event waits for the event to occur. The default, -1, waits indefinitely. The timing starts when you submit the Wait-Event command.

If the specified time is exceeded, the wait ends and the command prompt returns, even if the event has not been raised. No error message is displayed.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String
Outputs | System.String

Notes

Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.

Example 1

C:\PS>wait-event

This command waits for the next event that is raised.

Example 2

C:\PS>wait-event -sourceIdentifier "ProcessStarted"

This command waits for the next event that is raised and that has a source identifier of "ProcessStarted".

Example 3

C:\PS>$timer.Interval = 2000
C:\PS> $timer.Autoreset = $false
C:\PS> $timer.Enabled = $true; Wait-Event Timer.Elapsed

# After 2 seconds

EventIdentifier  : 12
Sender           : System.Timers.Timer
SourceEventArgs  : System.Timers.ElapsedEventArgs
SourceArgs       : {System.Timers.Timer, System.Timers.ElapsedEventArgs}
SourceIdentifier : Timer.Elapsed
TimeGenerated    : 6/10/2008 3:24:18 PM
MessageData      :
ForwardEvent     : False

Description
-----------
This command uses the Wait-Event cmdlet to wait for a timer event on a timer that is set for 2000 milliseconds.

Example 4

C:\PS>wait-event -sourceIdentifier "ProcessStarted" -timeout 90

This command waits up to 90 seconds for the next event that is raised and that has a source identifier of "ProcessStarted". If the specified time expires, the wait ends.

See Also

  • Register-ObjectEvent
  • Register-EngineEvent
  • Register-WmiEvent
  • Unregister-Event
  • Get-Event
  • New-Event
  • Remove-Event
  • Wait-Event
  • Get-EventSubscriber


Wait-Job

Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are complete.

Syntax

Wait-Job [[-InstanceId] <Guid[]>] [-Any] [-Timeout <int>] [<CommonParameters>]

Wait-Job [-Job] <Job[]> [-Any] [-Timeout <int>] [<CommonParameters>]

Wait-Job [[-Name] <string[]>] [-Any] [-Timeout <int>] [<CommonParameters>]

Wait-Job [-Id] <Int32[]> [-Any] [-Timeout <int>] [<CommonParameters>]

Wait-Job [-State {<NotStarted> | <Running> | <Completed> | <Failed> | <Stopped> | <Blocked>}] [-Any] [-Timeout <int>] [<CommonParameters>]

Description

The Wait-Job cmdlet waits for Windows PowerShell background jobs to complete before it displays the command prompt. You can wait until any background job is complete, or until all background jobs are complete, and you can set a maximum wait time for the job.

You can use Wait-Job to get background jobs that were started by using Start-Job or the AsJob parameter of Invoke-Command.

When the commands in the job are complete, Wait-Job displays the command prompt and returns a job object so that you can pipe it to another command.

Parameters

-Any

Displays the command prompt (and returns the job object) when any job completes. By default, Wait-Job waits until all of the specified jobs are complete before displaying the prompt.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Id <Int32[]>

Waits for jobs with the specified IDs.

The ID is an integer that uniquely identifies the job within the current session. It is easier to remember and type than the InstanceId, but it is unique only within the current session. You can type one or more IDs (separated by commas). To find the ID of a job, type "Get-Job" without parameters.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InstanceId <Guid[]>

Waits for jobs with the specified instance IDs. The default is all jobs.

An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use Get-Job.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Job <Job[]>

Waits for the specified jobs. Enter a variable that contains the job objects or a command that gets the job objects. You can also use a pipeline operator to send job objects to the Wait-Job cmdlet. By default, Wait-Job waits for all jobs created in the current session.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue, ByPropertyName)
Accept Wildcard Characters? | false

-Name <string[]>

Waits for jobs with the specified friendly name.

Required? | false
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-State <JobState>

Waits for jobs in the specified state. Valid values are NotStarted, Running, Completed, Stopped, Failed, and Blocked.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Timeout <int>

Determines the maximum wait time for each background job, in seconds. The default, -1, waits until the job completes, no matter how long it runs. The timing starts when you submit the Wait-Job command, not the Start-Job command.

If this time is exceeded, the wait ends and the command prompt returns, even if the job is still running. No error message is displayed.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.RemotingJob You can pipe a job object to Wait-Job.
Outputs | System.Management.Automation.RemotingJob Wait-Job returns job objects that represent the completed jobs. If the wait ends because the value of the Timeout parameter is exceeded, Wait-Job does not return any objects.

Example 1

C:\PS>get-job | wait-job

This command waits for all of the background jobs running in the session to complete.

Example 2

C:\PS>$s = new-pssession server01, server02, server03

C:\PS> invoke-command -session $s -scriptblock {start-job -name Date1 -scriptblock {get-date}}

C:\PS> $done = invoke-command -session $s -command {wait-job -name Date1}

C:\PS> $done.count
3

This example shows how to use the Wait-Job cmdlet with jobs started on remote computers by using the Start-Job cmdlet. Both the Start-Job and Wait-Job commands are submitted to the remote computer by using the Invoke-Command cmdlet.

This example uses Wait-Job to determine whether a Get-Date command running as a background job on three different computers is complete.

The first command creates a Windows PowerShell session (PSSession) on each of the three remote computers and stores them in the $s variable.

The second command uses the Invoke-Command cmdlet to run a Start-Job command in each of the three sessions in $s. All of the jobs are named Date1.

The third command uses the Invoke-Command cmdlet to run a Wait-Job command. This command waits for the Date1 jobs on each computer to complete. It stores the resulting collection (array) of job objects in the $done variable.

The fourth command uses the Count property of the array of job objects in the $done variable to determine how many of the jobs are complete.

Example 3

C:\PS>$s = new-pssession (get-content machines.txt)

C:\PS> $c = 'get-eventlog -log system | where {$_.EntryType -eq "error" -and $_.Source -eq "LSASRV"} | out-file errors.txt'

C:\PS> invoke-command -session $s -scriptblock {param($c)start-job -scriptblock {$c}} -ArgumentList $c

C:\PS> invoke-command -session $s -scriptblock {wait-job -any}

This example uses the Any parameter of Wait-Job to determine when the first of many background jobs running in the current session are complete. It also shows how to use the Wait-Job cmdlet to wait for remote jobs to complete.

The first command creates a PSSession on each of the computers listed in the Machines.txt file and stores the PSSessions in the $s variable. The command uses the Get-Content cmdlet to get the contents of the file. The Get-Content command is enclosed in parentheses to ensure that it runs before the New-PSSession command.

The second command stores a Get-EventLog command string (in quotation marks) in the $c variable.

The third command uses the Invoke-Command cmdlet to run a Start-Job command in each of the sessions in $s. The Start-Job command starts a background job that runs the command in $c.

Because the $c variable is on the local computer, the command uses the "param" keyword to declare the local variables in the command and the ArgumentList parameter to supply the values for those variables.

The fourth command uses the Invoke-Command cmdlet to run a Wait-Job command in the sessions. It uses the Wait-Job cmdlet to wait until the first job on the remote computers is complete.

Example 4

C:\PS>$s = new-pssession Server01, Server02, Server03

C:\PS> $jobs = invoke-command -session $s -scriptblock {start-job -script {get-date}}

C:\PS> $done = invoke-command -session $s -scriptblock {wait-job -timeout 30}

This example shows how to use the Timeout parameter of Wait-Job to set a maximum wait time for the jobs running on remote computers.

The first command creates a PSSession on each of three remote computers (Server01, Server02, and Server03), and it saves the PSSessions in the $s variable.

The second command uses the Invoke-Command cmdlet to run a Start-Job command in each of the PSSessions in $s. It saves the resulting job objects in the $jobs variable.

The third command uses the Invoke-Command cmdlet to run a Wait-Job command in each of the PSSessions in $s. The Wait-Job command determines whether all of the commands have completed within 30 seconds. It uses the Timeout parameter with a value of 30 (seconds) to establish the maximum wait time and saves the results of the command in the $done variable.

In this case, after 30 seconds, only the command on the Server02 computer has completed. Wait-Job ends the wait, displays the command prompt, and returns the object that represents the job that was completed.

The $done variable contains a job object that represents the job that ran on Server02.

Example 5

C:\PS>wait-job -id 1,2,5 -any

This command identifies three jobs by their IDs and waits until any of them are complete. The command prompt returns when the first job completes.

Example 6

C:\PS>wait-job -name DailyLog -timeout 120

This command waits 120 seconds (two minutes) for the DailyLog job to complete. If the job does not complete in the next two minutes, the command prompt returns anyway, and the job continues to run in the background.

Example 7

C:\PS>wait-job -name Job3

This Wait-Job command uses the job name to identify the job to wait for.

Example 8

C:\PS>C:\PS> $j = start-job -script {get-childitem *.ps1| where {$_lastwritetime -gt ((get-date) - (new-timespan -days 7))}}

C:\PS> $j | wait-job

This example shows how to use the Wait-Job cmdlet with jobs started on the local computer by using the Start-Job cmdlet.

These commands start a job that gets the Windows PowerShell script files that were added or updated in the last week.

The first command uses the Start-Job cmdlet to start a background job on the local computer. The job runs a Get-ChildItem command that gets all of the files with a ".ps1" file name extension that were added or updated in the last week.

The third command uses the Wait-Job cmdlet to wait until the job is complete. When the job completes, the command displays the job object, which contains information about the job.

Example 9

C:\PS>$s = new-pssession Server01, Server02, Server03

C:\PS> $j = invoke-command -session $s -scriptblock {get-process} -asjob

C:\PS> $j | wait-job

This example shows how to use the Wait-Job cmdlet with jobs started on remote computers by using the AsJob parameter of the Invoke-Command cmdlet. When using AsJob, the job is created on the local computer and the results are automatically returned to the local computer, even though the job runs on the remote computers.

This example uses Wait-Job to determine whether a Get-Process command running in the sessions on three remote computers is complete.

The first command creates PSSessions on three computers and stores them in the $s variable.

The second command uses the Invoke-Command cmdlet to run a Get-Process command in each of the three PSSessions in $s. The command uses the AsJob parameter to run the command asynchronously as a background job. The command returns a job object, just like the jobs started by using Start-Job, and the job object is stored in the $j variable.

The third command uses a pipeline operator (|) to send the job object in $j to the Wait-Job cmdlet. Notice that an Invoke-Command command is not required in this case, because the job resides on the local computer.

Example 10

C:\PS>get-job

Id   Name     State      HasMoreData     Location             Command
--   ----     -----      -----------     --------             -------
1    Job1     Completed  True            localhost,server01.. get-service
4    Job4     Completed  True            localhost            dir | where

C:\PS> wait-job -id 1

Description
-----------
This command waits for the job with an ID value of 1.

See Also

  • about_Jobs
  • about_Job_Details
  • about_Remote_Jobs
  • Start-Job
  • Get-Job
  • Receive-Job
  • Stop-Job
  • Remove-Job
  • Invoke-Command


Wait-Process

Waits for the processes to be stopped before accepting more input.

Syntax

Wait-Process [-Id] <Int32[]> [[-Timeout] <int>] [<CommonParameters>]

Wait-Process -InputObject <Process[]> [[-Timeout] <int>] [<CommonParameters>]

Wait-Process [-Name] <string[]> [[-Timeout] <int>] [<CommonParameters>]

Description

The Wait-Process cmdlet waits for one or more running processes to be stopped before accepting input. In the Windows PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can specify a process by process name or process ID (PID), or pipe a process object to Wait-Process.

Wait-Process works only on processes running on the local computer.

Parameters

-Id <Int32[]>

Specifies the process IDs of the processes. To specify multiple IDs, use commas to separate the IDs. To find the PID of a process, type "Get-Process". The parameter name ("Id") is optional.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-InputObject <Process[]>

Specifies the processes by submitting process objects. Enter a variable that contains the process objects, or type a command or expression that gets the process objects, such as a Get-Process command.

Required? | true
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Name <string[]>

Specifies the process names of the processes. To specify multiple names, use commas to separate the names.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByPropertyName)
Accept Wildcard Characters? | false

-Timeout <int>

Determines the maximum time, in seconds, that Wait-Process waits for the specified processes to stop. When this interval expires, the command displays a non-terminating error that lists the processes that are still running, and ends the wait.

Required? | false
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Diagnostics.Process You can pipe a process object to Wait-Process.
Outputs | None This cmdlet does not generate any output.

Notes

This cmdlet uses the WaitForExit method of the System.Diagnostics.Process class. For more information about this method, see the Microsoft .NET Framework SDK.

Example 1

C:\PS>$nid = (get-process notepad).id

C:\PS> stop-process -id $nid

C:\PS> wait-process -id $nid

These commands stop the Notepad process and then wait for the process to be stopped before proceeding with the next command.

The first command uses the Get-Process cmdlet to get the ID of the Notepad process. It saves it in the $nid variable.

The second command uses the Stop-Process cmdlet to stop the process with the ID saved in $nid.

The third command uses the Wait-Process cmdlet to wait until the Notepad process is stopped. It uses the ID parameter of Wait-Process to identify the process.

Example 2

C:\PS>$p = get-process notepad

C:\PS> wait-process -id $p.id

C:\PS> wait-process -name notepad

C:\PS> wait-process -inputobject $p

These commands show three different methods of specifying a process to the Wait-Process cmdlet. The first command gets the Notepad process and saves it in the $p variable.

The second command uses the ID parameter, the third command uses the Name parameter, and the fourth command uses the InputObject parameter.

These commands have the same results and can be used interchangeably.

Example 3

C:\PS>wait-process -name outlook, winword -timeout 30

This command waits 30 seconds for the Outlook and Winword processes to stop. If both processes are not stopped, the cmdlet displays a non-terminating error and the command prompt.

See Also

  • Get-Process
  • Start-Process
  • Stop-Process
  • Wait-Process
  • Debug-Process


Where-Object

Creates a filter that controls which objects will be passed along a command pipeline.

Syntax

Where-Object [-FilterScript] <scriptblock> [-InputObject <psobject>] [<CommonParameters>]

Description

The Where-Object cmdlet selects objects from the set of objects that are passed to it. It uses a script block as a filter and evaluates the script block for each object. If the result of the evaluation is True, the object is returned. If the result of the evaluation is not True, the object is ignored.

Parameters

-FilterScript <scriptblock>

Specifies the script block that is used to filter the objects. Enclose the script block in braces ( {} ).

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-InputObject <psobject>

Specifies the objects to be filtered. You can also pipe the objects to Where-Object.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe the objects to be filtered to Where-Object.
Outputs |

Example 1

C:\PS>get-service | where-object {$_.Status -eq "Stopped"}

This command gets a list of all services that are currently stopped. The "$" symbol represents each object that is passed to the Where-Object cmdlet.

Example 2

C:\PS>get-process | where-object {$_.workingset -gt 25000*1024}

This command lists processes that have a working set greater than 25,000 kilobytes (KB). Because the value of the WorkingSet property is stored in bytes, the value of 25,000 is multiplied by 1,024.

Example 3

C:\PS>get-process | where-object { $_.ProcessName -match "^p.*" }

This command gets the processes with a ProcessName property that begins with the letter "p". The match operator enables you to use regular expressions within a Where clause.

Example 4

C:\PS>get-process -name svchost | where-object {$True}

This command lists all of the processes named "svchost".

The Where-Object cmdlet evaluates the script block, which typically includes a reference to the object currently in the pipeline ($_),  and casts the results to a Boolean type: True or False. If the result is True, the object is returned. Otherwise, it is discarded.

In this case, the script block just returns True, so all the objects are returned.


Write-Debug

Writes a debug message to the console.

Syntax

Write-Debug [-Message] <string> [<CommonParameters>]

Description

The Write-Debug cmdlet writes debug messages to the console from a script or command.

By default, debug messages are not displayed in the console, but you can display them by using the Debug parameter or the $DebugPreference variable.

Parameters

-Message <string>

Specifies the debug message to send to the console.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains a debug message to Write-Debug.
Outputs | None Write-Debug writes only to the debug stream. It does not return any output.

Example 1

C:\PS>Write-Debug "Cannot open file."

This command writes a debug message. Because the value of $DebugPreference is "SilentlyContinue", the message is not displayed in the console.

Example 2

C:\PS>$DebugPreference

SilentlyContinue

C:\PS> Write-Debug "Cannot open file."
C:\PS>

C:\PS> Write-Debug "Cannot open file." -debug
DEBUG: Cannot open file.

Description
-----------
This example shows how to use the Debug common parameter to override the value of the $DebugPreference variable for a particular command.

The first command displays the value of the $DebugPreference variable, which is "SilentlyContinue", the default.

The second command writes a debug message but, because of the value of $DebugPreference, the message does not appear.

The third command writes a debug message. It uses the Debug common parameter to override the value of $DebugPreference and to display the debug messages resulting from this command.

As a result, even though the value of $DebugPreference is "SilentlyContinue", the debug message appears.

For more information about the Debug common parameter, see about_CommonParameters.

Example 3

C:\PS>$DebugPreference

SilentlyContinue

C:\PS> Write-Debug "Cannot open file."
C:\PS>

C:\PS> $DebugPreference = "Continue"

C:\PS> Write-Debug "Cannot open file."
DEBUG: Cannot open file.

Description
-----------
This command shows the effect of changing the value of the $DebugPreference variable on the display of debug messages.

The first command displays the value of the $DebugPreference variable, which is "SilentlyContinue", the default.

The second command writes a debug message but, because of the value of $DebugPreference, the message does not appear.

The third command assigns a value of "Continue" to the $DebugPreference variable.

The fourth command writes a debug message, which appears on the console.

For more information about $DebugPreference, see about_Preference_Variables.

See Also

  • Write-Verbose
  • Write-Error
  • Write-Host
  • Write-Progress
  • Write-Output
  • Write-Warning


Write-Error

Writes an object to the error stream.

Syntax

Write-Error -ErrorRecord <ErrorRecord> [-CategoryActivity <string>] [-CategoryReason <string>] [-CategoryTargetName <string>] [-CategoryTargetType <string>] [-RecommendedAction <string>] [<CommonParameters>]

Write-Error [-Message] <string> [-Category {<NotSpecified> | <OpenError> | <CloseError> | <DeviceError> | <DeadlockDetected> | <InvalidArgument> | <InvalidData> | <InvalidOperation> | <InvalidResult> | <InvalidType> | <MetadataError> | <NotImplemented> | <NotInstalled> | <ObjectNotFound> | <OperationStopped> | <OperationTimeout> | <SyntaxError> | <ParserError> | <PermissionDenied> | <ResourceBusy> | <ResourceExists> | <ResourceUnavailable> | <ReadError> | <WriteError> | <FromStdErr> | <SecurityError>}] [-ErrorId <string>] [-TargetObject <Object>] [-CategoryActivity <string>] [-CategoryReason <string>] [-CategoryTargetName <string>] [-CategoryTargetType <string>] [-RecommendedAction <string>] [<CommonParameters>]

Write-Error -Exception <Exception> [-Category {<NotSpecified> | <OpenError> | <CloseError> | <DeviceError> | <DeadlockDetected> | <InvalidArgument> | <InvalidData> | <InvalidOperation> | <InvalidResult> | <InvalidType> | <MetadataError> | <NotImplemented> | <NotInstalled> | <ObjectNotFound> | <OperationStopped> | <OperationTimeout> | <SyntaxError> | <ParserError> | <PermissionDenied> | <ResourceBusy> | <ResourceExists> | <ResourceUnavailable> | <ReadError> | <WriteError> | <FromStdErr> | <SecurityError>}] [-ErrorId <string>] [-Message <string>] [-TargetObject <Object>] [-CategoryActivity <string>] [-CategoryReason <string>] [-CategoryTargetName <string>] [-CategoryTargetType <string>] [-RecommendedAction <string>] [<CommonParameters>]

Description

The Write-Error cmdlet writes an error to the Windows PowerShell error stream. By default, errors are sent to the host program to be displayed, along with output.

You can write an error by submitting an error message string, an ErrorRecord object, or an Exception object. Use the other parameters of Write-Error to populate the error record.

Parameters

-Category <ErrorCategory>

Specifies the category of the error. The default value is NotSpecified.

For information about the error categories, see "ErrorCategory Enumeration" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143600.

Required? | false
Position? | named
Default Value | NotSpecified
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CategoryActivity <string>

Describes the action that caused the error.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CategoryReason <string>

Explains how or why the activity caused the error.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CategoryTargetName <string>

Specifies the name of the object that was being processed when the error occurred.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CategoryTargetType <string>

Specifies the .NET type of the object that was being processed when the error occurred.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ErrorId <string>

Specifies an ID string to identify the error. The string should be unique to the error.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ErrorRecord <ErrorRecord>

Specifies an error record object that includes properties that describe the error.

To get an error record object, use the New-Object cmdlet or take an error record object from the array in the $Error automatic variable.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Exception <Exception>

Specifies an exception that represents the error.

You can use an exception instead of specifying message text or an exception record.

Required? | true
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Message <string>

Specifies the message text of the error. If the text includes spaces or special characters, enclose it in quotation marks. You can also pipe a message string to Write-Error.

Required? | true
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-RecommendedAction <string>

Describes the action that the user should take to resolve or prevent the error.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-TargetObject <Object>

Specifies the object that was being processed when the error occurred. Enter the object (such as a string), a variable that contains the object, or a command that gets the object.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains an error message to Write-Error.
Outputs | Error object Write-Error writes only to the error stream. It does not return any objects.

Example 1

C:\PS>get-childitem | foreach-object { if ($_.gettype().tostring() -eq "Microsoft.Win32.RegistryKey") {write-error "Out-of-band object" -errorID B1 -targetobject $_ } else {$_ } }

This command writes an error when the Get-ChildItem cmdlet returns a Microsoft.Win32.RegistryKey object, such as the objects in the HKLM: or HKCU drives of the Windows PowerShell Registry provider.

Example 2

C:\PS>write-error  "Access denied."

This command writes an "Access denied" error. The command uses the Message parameter to specify the message, but omits the optional Message parameter name.

Example 3

C:\PS>write-error -message "Error: Too many input values." -category InvalidArgument

This command writes a error and specifies an error category.

See Also

  • Write-Debug
  • Write-Verbose
  • Write-Output
  • Write-Host
  • Write-Progress
  • Write-Warning


Write-EventLog

Writes an event to an event log.

Syntax

Write-EventLog [-LogName] <string> [-Source] <string> [-EventID] <int> [-Message] <string> [[-EntryType] {<Error> | <Warning> | <Information> | <SuccessAudit> | <FailureAudit>}] [-Category <Int16>] [-ComputerName <string>] [-RawData <Byte[]>] [<CommonParameters>]

Description

The Write-EventLog cmdlet writes an event to an event log.

To write an event to an event log, the event log must exist on the computer and the source must be registered for the event log.

The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.

Parameters

-Category <Int16>

Specifies a task category for the event. Enter an integer that is associated with the strings in the category message file for the event log.

Required? | false
Position? | named
Default Value | 1
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ComputerName <string>

Specifies a remote computer. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name of a remote computer.

This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-EventLog even if your computer is not configured to run remote commands.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-EntryType <EventLogEntryType>

Specifies the entry type of the event. Valid values are Error, Warning, Information, SuccessAudit, and FailureAudit. The default value is Information.

For a description of the values, see System.Diagnostics.EventLogEntryType in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143599.

Required? | false
Position? | 4
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-EventID <int>

Specifies the event identifier. This parameter is required.

Required? | true
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-LogName <string>

Specifies the name of the log to which the event is written. Enter the log name (the value of the Log property, not the LogDisplayName). Wildcard characters are not permitted. This parameter is required.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Message <string>

Specifies the event message. This parameter is required.

Required? | true
Position? | 5
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-RawData <Byte[]>

Specifies the binary data that is associated with the event, in bytes.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Source <string>

Specifies the event source, which is typically the name of the application that is writing the event to the log.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | System.Diagnostics.EventLogEntry Write-EventLog returns objects that represents the events in the logs.

Notes

To use Write-EventLog on Windows Vista and later versions of Windows, start Windows PowerShell with the "Run as administrator" option.

Example 1

C:\PS>write-eventlog -logname Application -source MyApp -eventID 3001 -entrytype Information -message "MyApp added a user-requested feature to the display." -category 1 -rawdata 10,20

This command writes an event from the MyApp source to the Application event log.

Example 2

C:\PS>write-eventlog -computername Server01 -logname Application -source MyApp -eventID 3001 -message "MyApp added a user-requested feature to the display."

This command writes an event from the MyApp source to the Application event log on the Server01 remote computer.

See Also

  • Clear-EventLog
  • Get-EventLog
  • Limit-EventLog
  • New-EventLog
  • Remove-EventLog
  • Show-Eventlog
  • Write-EventLog
  • Get-WinEvent


Write-Host

Writes customized output to a host.

Syntax

Write-Host [[-Object] <Object>] [-BackgroundColor {<Black> | <DarkBlue> | <DarkGreen> | <DarkCyan> | <DarkRed> | <DarkMagenta> | <DarkYellow> | <Gray> | <DarkGray> | <Blue> | <Green> | <Cyan> | <Red> | <Magenta> | <Yellow> | <White>}] [-ForegroundColor {<Black> | <DarkBlue> | <DarkGreen> | <DarkCyan> | <DarkRed> | <DarkMagenta> | <DarkYellow> | <Gray> | <DarkGray> | <Blue> | <Green> | <Cyan> | <Red> | <Magenta> | <Yellow> | <White>}] [-NoNewline] [-Separator <Object>] [<CommonParameters>]

Description

The Write-Host cmdlet customizes output. You can specify the color of text by using the ForegroundColor parameter, and you can specify the background color by using the BackgroundColor parameter. The Separator parameter lets you specify a string to use to separate displayed objects. The particular result depends on the program that is hosting Windows PowerShell.

Parameters

-BackgroundColor <ConsoleColor>

Specifies the background color. There is no default.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ForegroundColor <ConsoleColor>

Specifies the text color. There is no default.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-NoNewline

Specifies that the content displayed in the console does not end with a newline character.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Object <Object>

Objects to display in the console.

Required? | false
Position? | 1
Default Value | None
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

-Separator <Object>

String to the output between objects displayed on the console.

Required? | false
Position? | named
Default Value | None
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Object You can pipe objects to be written to the host.
Outputs | None Write-Host sends the objects to the host. It does not return any objects. However, the host might display the objects that Write-Host sends to it.

Example 1

C:\PS>write-host "no newline test " -nonewline

no newline test C:\PS>

Description
-----------
This command displays the input to the console, but because of the NoNewline parameter, the output is followed directly by the prompt.

Example 2

C:\PS>write-host (2,4,6,8,10,12) -Separator ", +2= "

2, +2= 4, +2= 6, +2= 8, +2= 10, +2= 12

Description
-----------
This command displays the even numbers from 2 through 12. The Separator parameter is used to add the string , +2= (comma, space, +, 2, =, space).

Example 3

C:\PS>write-host (2,4,6,8,10,12) -Separator ", -> " -foregroundcolor DarkGreen -backgroundcolor white

This command displays the even numbers from 2 through 12. It uses the ForegroundColor parameter to output dark green text and the BackgroundColor parameter to display a white background.

Example 4

C:\PS>write-host "Red on white text." -ForegroundColor red -BackgroundColor white

Red on white text.

Description
-----------
This command displays the string "Red on white text." The text is red, as defined by the ForegroundColor parameter. The background is white, as defined by the BackgroundColor parameter.

See Also

  • Write-Verbose
  • Write-Error
  • Write-Progress
  • Write-Debug
  • Write-Output
  • Write-Warning
  • Out-Host


Write-Output

Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console.

Syntax

Write-Output [-InputObject] <PSObject[]> [<CommonParameters>]

Description

The Write-Output cmdlet sends the specified object down the pipeline to the next command. If the command is the last command in the pipeline, the object is displayed in the console.

Write-Output sends objects down the primary pipeline, also known as the "output stream" or the "success pipeline." To send error objects down the error pipeline, use Write-Error.

This cmdlet is typically used in scripts to display strings and other objects on the console. However, because the default behavior is to display the objects at the end of a pipeline, it is generally not necessary to use the cmdlet. For example, "Get-Process | write-output" is equivalent to "Get-Process".

Parameters

-InputObject <PSObject[]>

Specifies the objects to send down the pipeline. Enter a variable that contains the objects, or type a command or expression that gets the objects.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.Management.Automation.PSObject You can pipe objects to Write-Output.
Outputs | System.Management.Automation.PSObject Write-Output returns the objects that are submitted as input.

Example 1

C:\PS>$p = get-process

c:\PS> write-output $p

c:\PS> $p

These commands get objects representing the processes running on the computer and display the objects on the console.

Example 2

C:\PS>write-output "test output" | get-member

This command pipes the "test output" string to the Get-Member cmdlet, which displays the members of the String class, demonstrating that the string was passed along the pipeline.

See Also

  • Write-Debug
  • Write-Verbose
  • Write-Error
  • Write-Progress
  • Write-Host
  • Write-Warning
  • Tee-Object


Write-Progress

Displays a progress bar within a Windows PowerShell command window.

Syntax

Write-Progress [-Activity] <string> [-Status] <string> [[-Id] <int>] [-Completed] [-CurrentOperation <string>] [-ParentId <int>] [-PercentComplete <int>] [-SecondsRemaining <int>] [-SourceId <int>] [<CommonParameters>]

Description

The Write-Progress cmdlet displays a progress bar in a Windows PowerShell command window that depicts the status of a running command or script. You can select the indicators that the bar reflects and the text that appears above and below the progress bar.

Parameters

-Activity <string>

Specifies the first line of text in the heading above the status bar. This text describes the activity whose progress is being reported.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Completed

Indicates whether the progress bar is visible. If this parameter is omitted, Write-Progress displays progress information.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-CurrentOperation <string>

Specifies the line of text below the progress bar. This text describes the operation that is currently taking place.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Id <int>

Specifies an ID that distinguishes each progress bar from the others. Use this parameter when you are creating more than one progress bar in a single command. If the progress bars do not have different IDs, they are superimposed instead of being displayed in a series.

Required? | false
Position? | 3
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-ParentId <int>

Identifies the parent activity of the current activity. Use the value -1 if the current activity has no parent activity.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-PercentComplete <int>

Specifies the percentage of the activity that is completed. Use the value -1 if the percentage complete is unknown or not applicable.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SecondsRemaining <int>

Specifies the projected number of seconds remaining until the activity is completed. Use the value -1 if the number of seconds remaining is unknown or not applicable.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-SourceId <int>

Identifies the source of the record.

Required? | false
Position? | named
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

-Status <string>

Specifies the second line of text in the heading above the status bar. This text describes current state of the activity.

Required? | true
Position? | 2
Default Value | none
Accept Pipeline Input? | false
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | None You cannot pipe input to this cmdlet.
Outputs | None Write-Progress does not generate any output.

Notes

If the progress bar does not appear, check the value of the $ProgressPreference variable. If the value is set to SilentlyContinue, the progress bar is not displayed. For more information about Windows PowerShell preferences, see about_Preference_Variables.

The parameters of the cmdlet correspond to the properties of the ProgressRecord class (System.Management.Automation.ProgressRecord). For more information, see the ProgressRecord topic in the Windows PowerShell Software Development Kit (SDK).

Example 1

C:\PS>for ($i = 1; $i -lt 101; $i++ )
{for ($j=0;$j -lt 10000;$j++) {} write-progress -activity "Search in Progress" -status "% Complete:" -percentcomplete $i;}

This command displays the progress of two nested For loops. The first loop counts to 100. For each increment of that loop, the second loop counts to 10,000.
The Write-Progress command includes a status bar heading ("activity"), a status line, and the variable $i (the counter in the For loop), which indicates the relative completeness of the task.

Example 2

C:\PS>for($i = 1; $i -lt 101; $i++ ) {write-progress -activity Updating -status progress-> -percentcomplete $i -currentOperation OuterLoop} for($i = 1; $i -lt 101; $i++ ) {write-progress -activity Updating -status progress -percentcomplete $i -id  1 -currentOperation InnerLoop}

Updating
   progress ->
   [oooooooooooooooooo                                                   ]

   OutsideLoop

Updating
  progress
  [oooooooooooooooooo                                                    ]

  InnerLoop

Description
-----------
This example displays the progress of two nested For loops, each of which is represented by a progress bar.

The Write-Progress command for the second progress bar includes the Id parameter that distinguishes it from the first progress bar. Without the Id parameter, the progress bars would be superimposed on each other instead of being displayed one below the other.

Example 3

C:\PS>$events = get-eventlog -logname system

C:\PS> $events | foreach-object -begin {clear-host;$i=0;$out=""} `
-process {if($_.message -like "*bios*") {$out=$out + $_.Message};
$i = $i+1;`
write-progress -activity "Searching Events" `
-status "Progress:" -percentcomplete ($i/$events.count*100)} `
-end {$out}

This command displays the progress of a command to find the string "bios" in the System event log.

In the first line of the command, the Get-EventLog cmdlet gets the events in the System log and stores them in the $events variable.

In the second line, the events are piped to the ForEach-Object cmdlet. Before processing begins, the Clear-Host cmdlet is used to clear the screen, the $i counter variable is set to zero, and the $out output variable is set to the empty string.

In the third line, which is the Process script block of the ForEach-Object cmdlet, the cmdlet searches the message property of each incoming object for "bios". If the string is found, the message is added to $out.

In the fourth line, the $i counter variable is incremented to record that another event has been examined.

The fifth line uses the Write-Progress cmdlet with values for the Activity and Status text fields that create the first and second lines of the progress bar heading, respectively. The PercentComplete parameter value is calculated by dividing the number of events that have been processed ($i) by the total number of events retrieved ($events.count) and then multiplying that result by 100.

In the last line, the End parameter of the ForEach-Object cmdlet is used to display the messages that are stored in the $out variable.

See Also

  • Write-Verbose
  • Write-Error
  • Write-Host
  • Write-Debug
  • Write-Output
  • Write-Warning


Write-Verbose

Writes text to the verbose message stream.

Syntax

Write-Verbose [-Message] <string> [<CommonParameters>]

Description

The Write-Verbose cmdlet writes text to the verbose message stream in Windows PowerShell. Typically, the verbose message stream is used to deliver information about command processing that is used for debugging a command.

By default, the verbose message stream is not displayed, but you can display it by changing the value of the $VerbosePreference variable or using the Verbose common parameter in any command.

Parameters

-Message <string>

Specifies the message to display. This parameter is required. You can also pipe a message string to Verbose-Message.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains the message to Write-Verbose.
Outputs | None Write-Verbose writes only to the verbose message stream.

Example 1

C:\PS>Write-Verbose -message "Searching the Application Event Log."

C:\PS> Write-Verbose -message "Searching the Application Event Log." -verbose

Description
-----------
These commands use the Write-Verbose cmdlet to display a status message. By default, the message is not displayed.

The second command uses the Verbose common parameter, which displays any verbose messages, regardless of the value of the $VerbosePreference variable.

Example 2

C:\PS>$VerbosePreference = "Continue"

C:\PS> Write-Verbose "Copying file $filename"

These commands use the Write-Verbose cmdlet to display a status message. By default, the message is not displayed.

The first command assigns a value of "Continue" to the $VerbosePreference preference variable. The default value, "SilentlyContinue", suppresses verbose messages.

The second command writes a verbose message.

See Also

  • Write-Error
  • Write-Warning
  • about_Preference_Variables


Write-Warning

Writes a warning message.

Syntax

Write-Warning [-Message] <string> [<CommonParameters>]

Description

The Write-Warning cmdlet writes a warning message to the Windows PowerShell host. The response to the warning depends on the value of the user's $WarningPreference variable and the use of the WarningAction common parameter.

Parameters

-Message <string>

Specifies the warning message.

Required? | true
Position? | 1
Default Value | none
Accept Pipeline Input? | true (ByValue)
Accept Wildcard Characters? | false

<CommonParameters>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters.

Inputs and Outputs

The input type is the type of the objects that you can pipe to the cmdlet. The return type is the type of the objects that the cmdlet returns.

Inputs | System.String You can pipe a string that contains the warning to Write-Warning.
Outputs | None Write-Warning writes only to the warning stream. It does not generate any other output.

Notes

The default value for the $WarningPreference variable is "Continue", which displays the warning and then continues executing the command. To determine valid values for a preference variable such as $WarningPreference, set it to a string of random characters, such as "abc". The resulting error message will list the valid values.

Example 1

C:\PS>write-warning "This is only a test warning."

This command displays the message "WARNING: This is only a test warning."

Example 2

C:\PS>$w = "This is only a test warning."

C:\PS> $w | write-warning

This example shows that you can use a pipeline operator (|) to send a string to Write-Warning. You can save the string in a variable, as shown in this command, or pipe the string directly to Write-Warning.

Example 3

C:\PS>$warningpreference

Continue

C:\PS> write-warning "This is only a test warning."
This is only a test warning.

C:\PS> $warningpreference = "SilentlyContinue"

C:\PS> write-warning "This is only a test warning."
C:\PS>

C:\PS> $warningpreference = "Stop"

C:\PS> write-warning "This is only a test warning."
WARNING: This is only a test message.
Write-Warning : Command execution stopped because the shell variable "WarningPreference" is set to Stop.
At line:1 char:14
+ write-warning <<<<  "This is only a test message."

Description
-----------
This example shows the effect of the value of the $WarningPreference variable on a Write-Warning command.

The first command displays the default value of the $WarningPreference variable, which is "Continue". As a result, when you write a warning, the warning message is displayed and execution continues.

When you change the value of the $WarningPreference variable, the effect of the Write-Warning command changes again. A value of "SilentlyContinue" suppresses the warning. A value of "Stop" displays the warning and then stops execution of the command.

For more information about the $WarningPreference variable, see about_Preference_Variables.

Example 4

C:\PS>write-warning "This is only a test warning." -warningaction Inquire

WARNING: This is only a test warning.

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

Description
-----------
This example shows the effect of the WarningAction common parameter on a Write-Warning command. You can use the WarningAction common parameter with any cmdlet to determine how Windows PowerShell responds to warnings resulting from that command. The WarningAction common parameter overrides the value of the $WarningPreference only for that particular command.

This command uses the Write-Warning cmdlet to display a warning. The WarningAction common parameter with a value of "Inquire" directs the system to prompt the user when the command displays a warning.

For more information about the WarningAction common parameter, see about_CommonParameters.

See Also

  • about_Preference_Variables
  • about_CommonParameters
  • Write-Debug
  • Write-Error
  • Write-Host
  • Write-Output
  • Write-Progress
  • Write-Verbose


Windows PowerShell Provider Help Topics

Windows PowerShell providers are .NET programs that make the data in a specialized data store available in Windows PowerShell so that you can easily view and manage it. The data that a provider exposes appears in a drive, much like a file system drive. For more information, see about_Providers.

This section contains the help topics for the providers that are installed with Windows PowerShell.

Provider | Description
Alias Provider | Provides access to the Windows PowerShell aliases and their values.
Certificate Provider | Provides read-only access to X509 certificate stores and certificates.
Environment Provider | Provides access to the Windows environment variables.
FileSystem Provider | Provides access to files and directories.
Function Provider | Provides access to the functions defined in Windows PowerShell.
Registry Provider | Provides access to the system registry keys and values.
Variable Provider | Provides access to Windows PowerShell variables and their values.
WS-Management Provider | Provides access to WSMan configuration information.

See Also

  • Windows PowerShell Cmdlet Help Topics
  • Windows PowerShell About Help Topics
  • Windows PowerShell Getting Started Guide
  • PowerShell.exe Console Help
  • Windows PowerShell SDK


Alias Provider

PROVIDER NAME

Alias

DRIVES

Alias:

SHORT DESCRIPTION

Provides access to the Windows PowerShell aliases and the values that they represent.

DETAILED DESCRIPTION

The Windows PowerShell Alias Provider lets you get, add, change, clear, and delete aliases in Windows PowerShell.

An alias is an alternate name for a cmdlet, function, or executable file. Windows PowerShell includes a set of built-in aliases. And, you can add your own aliases to the current session and to your Windows PowerShell profile.

The Alias Provider is a flat namespace that contains only the alias objects. The aliases have no child items.

Each alias is an instance of the System.Management.Automation.AliasInfo class.

The Alias Provider exposes its data store in the Alias: drive. To work with aliases, you can change your location to the Alias: drive by using the following command:

Set-Location alias:

Or, you can work from any other Windows PowerShell drive. To reference an alias from another location, use the Alias: drive name in the path.

Windows PowerShell includes a set of cmdlets that are designed to view and to change aliases:

Export-Alias

Get-Alias

Import-Alias

New-Alias

Set-Alias

When you use these cmdlets, you do not need to specify the Alias: drive in the name.

The Alias Provider supports all the cmdlets that have the Item noun except for the Invoke-Item cmdlet. And, it supports the Get-Content and Set-Content cmdlets. The Alias Provider does not support the cmdlets that have the ItemProperty noun. And, the Alias Provider does not support the Filter parameter in any cmdlet.

All changes to the aliases affect the current session only. To save the changes, add the changes to the Windows PowerShell profile. Or, use the Export-Alias and Import-Alias cmdlets.

EXAMPLES

Getting to the Alias: Drive

-------------------------- EXAMPLE 1 --------------------------

This command changes the current location to the Alias: drive. You can use this command from any drive in Windows PowerShell. To return to a file system drive, type the drive name. For example, type "set-location c:".

set-location alias:

Getting Aliases

-------------------------- EXAMPLE 1 --------------------------

This command gets a list of all the aliases in the current session. You can use this command in any Windows PowerShell drive.

get-item -path alias:

-------------------------- EXAMPLE 2 --------------------------

This command gets the "ls" alias. Because it includes the path, you can use it in any Windows PowerShell drive.

get-item -path alias:ls

If you are in the Alias: drive, you can omit the drive name from the path.

-------------------------- EXAMPLE 3 --------------------------

This command gets a list of the aliases that are associated with the Get-ChildItem cmdlet. It uses the Definition property, which stores the cmdlet name.

get-item -path alias:* | where-object {$_.Definition -eq "Get-Childitem"}

When the aliased item is an executable file, the Definition contains the fully qualified path of the file.

-------------------------- EXAMPLE 4 --------------------------

This command gets the list of all the aliases when the current location is the Alias: drive. It uses a wildcard character (*) to indicate all the contents of the current location.

get-item -path *

In the Alias: drive, a dot (.), which represents the current location, and a wildcard character (*), which represents all items in the current location, have the same effect. For example, "get-item -path ." or "get-item *" produce the same result.

Creating a New Alias

-------------------------- EXAMPLE 1 --------------------------

This command creates the "serv" alias for the Get-Service cmdlet. Because the current location is in the Alias: drive, the value of the Path parameter is a dot (.). The dot represents the current location.

This command also uses the Options dynamic parameter to set the AllScope and Constant options on the alias. The Options parameter is available in the New-Item cmdlet only when you are in the Alias: drive.

new-item -path . -name serv -value Get-Service -Options "AllScope,Constant"

If you are in the Alias: drive, you can omit the drive name from the path.

-------------------------- EXAMPLE 2 --------------------------

You can create an alias for any item that invokes a command. This command creates the "np" alias for Notepad.exe.

new-item -path alias:np -value c:\windows\notepad.exe

-------------------------- EXAMPLE 3 --------------------------

You can create an alias for any function. You can use this feature to create an alias that includes both a cmdlet and its parameters.

The first command creates the CD32 function, which changes the current directory to the System32 directory. The second command creates the "go" alias for the CD32 function. The semi-colon (;) is the command separator.

When the command is complete, you can use either "CD32" or "go" to invoke the function.

function CD32 {set-location -path c:\windows\system32} set-item -path alias:go -value CD32

Displaying the Properties and Methods of Aliases

-------------------------- EXAMPLE 1 --------------------------

This command uses the Get-Item cmdlet to get all aliases. The pipeline operator (|) sends the results to the Get-Member cmdlet, which displays the methods and properties of the object.

get-item -path alias:* | get-member

When you pipe a collection of objects to Get-Member, such as the collection of aliases in the Alias: drive, Get-Member evaluates each object in the collection separately. Then, Get-Member returns information about each object type that it finds. If all the objects are of the same type, it returns information about the single object type. In this case, all the aliases are AliasInfo objects. To get information about the collection of AliasInfo objects, use the InputObject parameter of Get-Member. For example, use the following command: Get-Member -InputObject (Get-Item alias:*) When you use InputObject, Get-Member evaluates the collection, not the objects in the collection.

-------------------------- EXAMPLE 2 --------------------------

This command lists the values of the properties of the "dir" alias. It uses the Get-Item cmdlet to get an object that represents the "dir" alias. The pipeline operator (|) sends the results to the Format-List command. The Format-List command uses the Property parameter with a wildcard character (*) to format and display the values of all the "dir" alias properties.

get-item alias:dir | format-list -property *

Changing the Properties of an Alias

-------------------------- EXAMPLE 1 --------------------------

You can use the Set-Item cmdlet with the Options dynamic parameter to change the value of the Options property of an alias.

This command sets the AllScope and ReadOnly options for the "dir" alias. The command uses the Options dynamic parameter of the Set-Item cmdlet. The Options parameter is available in Set-Item only when you use it with the Alias or Function provider.

set-item -path alias:dir -options "AllScope,ReadOnly"

-------------------------- EXAMPLE 2 --------------------------

This command uses the Set-Item cmdlet to change the "gp" alias so that it represents the Get-Process cmdlet instead of the Get-ItemProperty cmdlet. The Force parameter is required because the value of the Options property of the "gp" alias is set to ReadOnly. Because the command is submitted from within the Alias: drive, the drive is not specified in the path.

set-item -path gp -value get-process -force

The change affects the four properties that define the association between the alias and the command. To view the effect of the change, type the following command: get-item -path gp | format-list -property *

-------------------------- EXAMPLE 3 --------------------------

This command uses the Rename-Item cmdlet to change the "popd" alias to "pop".

rename-item -path alias:popd -newname pop

Copying an Alias

-------------------------- EXAMPLE 1 --------------------------

This command copies the pushd alias so that a new push alias is created for the Push-Location cmdlet.

copy-item -path alias:pushd -destination alias:push

When the new alias is created, its Description property has a null value. And, its Option property has a value of None. If the command is issued from within the Alias: drive, you can omit the drive name from the value of the Path parameter.

Deleting an Alias

-------------------------- EXAMPLE 1 --------------------------

This command deletes the serv alias from the current session. You can use this command in any Windows PowerShell drive.

remove-item -path alias:serv

If you are in the Alias: drive, you can omit the drive name from the path.

-------------------------- EXAMPLE 2 --------------------------

This command deletes aliases that begin with "s". It does not delete read-only aliases.

clear-item -path alias:s*

-------------------------- EXAMPLE 3 --------------------------

This command deletes all aliases from the current session, except those with a value of Constant for their Options property. Without the Force parameter, the command does not delete aliases whose Options property has a value of ReadOnly.

remove-item alias:* -force

DYNAMIC PARAMETERS

Dynamic parameters are cmdlet parameters that are added by a Windows PowerShell provider and are available only when the cmdlet is being used in the provider-enabled drive.

Options <System.Management.Automation.ScopedItemOptions>

Determines the value of the Options property of an alias.

Value | Description
None | No options. This value is the default.
Constant | The alias cannot be deleted and its properties cannot be changed. Constant is available only when you create an alias. You cannot change the option of an existing alias to Constant.
Private | The alias is visible only in the current scope, not in the child scopes.
ReadOnly | The properties of the alias cannot be changed except by using the Force parameter. You can use Remove-Item to delete the alias.
AllScope | The alias is copied to any new scopes that are created.

Cmdlets supported:

  • New-Item

  • Set-Item

See Also

  • about_Aliases
  • about_Providers


Certificate Provider

PROVIDER NAME

Certificate

DRIVES

Cert:

SHORT DESCRIPTION

Provides access to X.509 certificate stores and certificates from within Windows PowerShell.

DETAILED DESCRIPTION

The Windows PowerShell security strategy supports the use of Authenticode signatures to sign scripts using X.509-encoded digital public key certificates. The signing features of Windows PowerShell are not intended to be complete, but they enable users to sign scripts and enable Windows PowerShell to recognize signed and unsigned scripts and to determine whether the scripts originate on the Internet.

The Windows PowerShell Certificate Provider lets you navigate the certificate namespace and view the certificate stores and certificates. It also lets you copy, move, and delete certificates and certificate stores, and it lets you open the Certificates snap-in for the Microsoft Management Console (MMC).

The Certificate Provider exposes the certificate namespace as the Cert: drive in Windows PowerShell. The Cert: drive has the following three levels:

-- Store locations (Microsoft.PowerShell.Commands.X509StoreLocation), which are high-level containers that group the certificates for the current user and for all users. Each system has a CurrentUser and LocalMachine (all users) store location.

-- Certificates stores (System.Security.Cryptography.X509Certificates.X509Store), which are physical stores in which certificates are saved and managed.

-- X.509 certificates (System.Security.Cryptography.X509Certificates.X509Certificate2), each of which represent an X.509 certificate on the computer. Certificates are identified by their thumbprints.

The Windows PowerShell Certificate Provider supports the Set-Location, Get-Location, Get-Item, Get-ChildItem, and Invoke-Item cmdlets.

In addition, the Windows PowerShell Security snap-in (Microsoft.PowerShell.Security), which includes the Certificate Provider, also includes snap-ins to get and set Authenticode signatures and to get certificates. For a list of cmdlets in the Security snap-in, type "Get-Command -module *security".

EXAMPLES

Navigating the Cert: Drive

-------------------------- EXAMPLE 1 --------------------------

This command uses the Set-Location cmdlet to change the current location to the Cert: drive.

set-location cert:

-------------------------- EXAMPLE 2 --------------------------

This command uses the Set-Location command to change the current location to the Root certificate store in the LocalMachine store location. Use a backslash (\) or a forward slash (/) to indicate a level of the Cert: drive.

set-location -path LocalMachine\Root

If you are not in the Cert: drive, begin the path with the drive name.

Displaying the Contents of the Cert: Drive

-------------------------- EXAMPLE 1 --------------------------

This command uses the Get-ChildItem cmdlet to display the certificate stores in the CurrentUser certificate store location.

get-childitem -path cert:\CurrentUser

If you are in the Cert: drive, you can omit the drive name.

-------------------------- EXAMPLE 2 --------------------------

This command uses the Get-ChildItem cmdlet to display the certificates in the My certificate store.

get-childitem -path cert:\CurrentUser\My

If you are in the Cert: drive, you can omit the drive name.

-------------------------- EXAMPLE 3 --------------------------

This command uses the Get-Item cmdlet to get the "My" certificate store and the Property parameter of Format-List with a wildcard character (*) to display all of the properties of the store.

get-item -path cert:\CurrentUser\My | format-list *

-------------------------- EXAMPLE 4 --------------------------

This command gets a certificate and displays all of its properties. It uses the Get-ChildItem cmdlet to get the certificate and the Property parameter of Format-List with a wildcard character (*) to display all of the properties of the certificate.

The certificate is identified by its thumbprint.

get-childitem -path cert:\CurrentUser\my\6B8223358119BB08840DEE50FD8AF9EA776CE66B | format-list -property *

-------------------------- EXAMPLE 5 --------------------------

This command uses the Get-ChildItem cmdlet to get all of the certificates on the computer and its CodeSigningCert dynamic parameter to get only the certificates that have code-signing authority.

get-childitem -path * -codesigningcert -recurse

Opening the Certificates MMC Snap-in

-------------------------- EXAMPLE 1 --------------------------

This command opens the Certificates MMC snap-in to manage the specified certificate.

invoke item cert:\CurrentUser\my\6B8223358119BB08840DEE50FD8AF9EA776CE66B

DYNAMIC PARAMETERS

Dynamic parameters are cmdlet parameters that are added by a Windows PowerShell provider and are available only when the cmdlet is being used in the provider-enabled drive.

CodeSigningCert <System.Management.Automation.SwitchParameter>

Gets only those certificates with code-signing authority.

Cmdlets supported:

  • Get-Item

  • Get-ChildItem

See Also

  • about_Providers
  • about_Signing
  • Get-AuthenticodeSignature
  • Set-AuthenticodeSignature
  • Get-PfxCertificate


Environment Provider

PROVIDER NAME

Environment

DRIVES

Env:

SHORT DESCRIPTION

Provides access to the Windows environment variables.

DETAILED DESCRIPTION

The Windows PowerShell Environment Provider lets you get, add, change, clear, and delete Windows environment variables in Windows PowerShell.

The Environment Provider is a flat namespace that contains only objects that represent the environment variables. The variables have no child items.

Each environment variable is an instance of the System.Collections.DictionaryEntry class. The name of the variable is the dictionary key. The value of the environment variable is the dictionary value.

The Environment Provider exposes its data store in the Env: drive. To work with environment variables, change your location to the Env: drive ("set-location env:"), or work from another Windows PowerShell drive. To reference an environment variable from another location, use the Env: drive name in the path.

The environment Variable Provider supports all the cmdlets that contain the Item noun except for Invoke-Item. And, it supports the Get-Content and Set-Content cmdlets. However, it does not support the cmdlets that contain the ItemProperty noun, and it does not support the Filter parameter in any cmdlet.

Environment variables must conform to the usual naming standards. Additionally, the name cannot include the equal sign (=).

Changes to the environment variables affect the current session only. To save the changes, add the changes to the Windows PowerShell profile, or use Export-Console to save the current session.

EXAMPLES

Getting to the Env: Drive

-------------------------- EXAMPLE 1 --------------------------

This command changes the current location to the Env: drive:

set-location env:

You can use this command from any drive in Windows PowerShell. To return to a file system drive, type the drive name. For example, type: set-location c:

Getting Environment Variables

-------------------------- EXAMPLE 1 --------------------------

This command lists all the environment variables in the current session:

get-childitem -path env:

You can use this command from any Windows PowerShell drive.

-------------------------- EXAMPLE 2 --------------------------

This command gets the WINDIR environment variable:

get-childitem -path env:windir

-------------------------- EXAMPLE 3 --------------------------

This command gets a list of all the environment variables in the current session and then sorts them by name:

get-childitem  | sort-object -property name

By default, the environment variables appear in the order that Windows PowerShell discovers them. This command is submitted in the Env: drive. When you run this command from another drive, add the Path parameter with a value of Env:.

Creating a New Environment Variable

-------------------------- EXAMPLE 1 --------------------------

This command creates the USERMODE environment variable with a value of Non-Admin:

new-item -path . -name USERMODE -value Non-Admin

Because the current location is in the Env: drive, the value of the Path parameter is a dot (.). The dot represents the current location. If you are not in the Env: drive, the value of the Path parameter would be Env:.

Displaying the Properties and Methods of Environment Variables

-------------------------- EXAMPLE 1 --------------------------

This command uses the Get-ChildItem cmdlet to get all the environment variables:

get-childitem -path env: | get-member

The pipeline operator (|) sends the results to Get-Member, which displays the methods and properties of the object. When you pipe a collection of objects to Get-Member, such as the collection of environment variables in the Env: drive, Get-Member evaluates each object in the collection separately. Get-Member then returns information about each object type that it finds. If all the objects are of the same type, it returns information about the single object type. In this case, all the environment variables are DictionaryEntry objects. To get information about the collection of DictionaryEntry objects, use the InputObject parameter of Get-Member. For example, type: get-member -inputobject (get-childitem env:) When you use the InputObject parameter, Get-Member evaluates the collection, not the objects in the collection.

-------------------------- EXAMPLE 2 --------------------------

This command lists the values of the properties of the WINDIR environment variable:

get-item env:windir | format-list -property *

It uses the Get-Item cmdlet to get an object that represents the WINDIR environment variable. The pipeline operator (|) sends the results to the Format-List command. It uses the Property parameter with a wildcard character (*) to format and display the values of all the properties of the WINDIR environment variable.

Changing the Properties of an Environment Variable

-------------------------- EXAMPLE 1 --------------------------

This command uses the Rename-Item cmdlet to change the name of the USERMODE environment variable that you created to USERROLE:

rename-item -path env:USERMODE -newname USERROLE

This change affects the Name, Key, and PSPath properties of the DictionaryEntry object. Do not change the name of an environment variable that the system uses. Although these changes affect only the current session, they might cause the system or a program to operate incorrectly.

-------------------------- EXAMPLE 2 --------------------------

This command uses the Set-Item cmdlet to change the value of the USERROLE environment variable to Administrator:

set-item -path env:USERROLE -value Administrator

Copying an Environment Variable

-------------------------- EXAMPLE 1 --------------------------

This command copies the value of the USERROLE environment variable to the USERROLE2 environment variable:

copy-item -path env:USERROLE -destination env:USERROLE2

Deleting an environment variable

-------------------------- EXAMPLE 1 --------------------------

This command deletes the USERROLE2 environment variable from the current session:

remove-item -path env:USERROLE2

You can use this command in any Windows PowerShell drive. If you are in the Env: drive, you can omit the drive name from the path.

-------------------------- EXAMPLE 2 --------------------------

This command deletes the USERROLE environment variable.

clear-item -path env:USERROLE

See Also

  • about_Providers


FileSystem Provider

PROVIDER NAME

FileSystem

DRIVES

C, D

SHORT DESCRIPTION

Provides access to files and directories.

DETAILED DESCRIPTION

The Windows PowerShell FileSystem Provider lets you get, add, change, clear, and delete files and directories in Windows PowerShell.

The FileSystem Provider exposes Windows PowerShell drives that correspond to the logical drives configured on your computer, including drives mapped to network shares. For example, a computer with one floppy disk drive, one hard disk drive, and one mapped network shared directory might have drives named A, C, and Z. The FileSystem Provider exposes Windows PowerShell drives that correspond directly to A, C, and Z, allowing you to reference these drives from within Windows PowerShell. For example, to reference drive C, you use C:, as shown in the following example:

Get-ChildItem c:

The command returns all the contents on the C drive, including files and directories. When you reference a specific directory or file through the FileSystem Provider, you must provide the information necessary to identify that directory or file. This means that, in some cases, you must provide a fully qualified name. A fully qualified name includes the drive name (along with a colon), any directory and subdirectory names, and the file name (when applicable). For instance, the following example shows the fully qualified name for the Shell.dll file, which is located in the System32 subdirectory of the Windows directory on the C drive:

c:\windows\system32\shell.dll

As you can see, each element of the fully qualified name is separated by a backslash (\). Windows PowerShell also allows you to use a forward slash (/) to be consistent with a variety of other shells.

In some cases, you do not need to supply a fully-qualified name when referencing a file or directory. For example, if you want to access a file in your current working location, you need to provide only the file name. If your current working location is c:\windows, you can view a list of all the .dll files in that directory by using the following command:

Get-ChildItem *.dll

If your working directory is something other than c:\windows, such as c:\program files\Windows PowerShell, your command might need to include the fully qualified name:

Get-ChildItem c:\windows\*.dll

In some cases, you can use relative references to a location. If your working location is c:\windows, and you want to view a list of .dll files in the c:\windows\system32 directory, you can use the following command:

Get-ChildItem .\system32\*.dll

The period before \system32 represents the current working location.

In some situations, your current working location will be on a drive other than a FileSystem drive. If this is the case, you must always include the name of the target drive in your reference. For example, suppose that your current working location is the env: drive. To view the contents of the C drive, you would use the following command:

Get-ChildItem c:

EXAMPLES

Navigating the File System

-------------------------- EXAMPLE 1 --------------------------

This command gets the current location:

get-location

The Get-Location cmdlet includes the functionality of commands like the cd command in the Windows Command Prompt and the pwd command in UNIX. For more information, type: get-help get-location

-------------------------- EXAMPLE 2 --------------------------

This command sets the current location:

set-location C:

Getting File and Directory Information

-------------------------- EXAMPLE 1 --------------------------

This command gets all the files and directories in the current directory:

get-childitem

By default, the Get-ChildItem cmdlet does not recurse. If files and folders are present in the current directory when you run this command, a System.IO.FileInfo object and a System.IO.DirectoryInfo object are returned.

-------------------------- EXAMPLE 2 --------------------------

This command gets all the files and directories in the current directory by using Get-ChildItem:

get-childitem | where-object {!$_.psiscontainer}

It pipes the results to Where-Object, which examines the PSIsContainer property and lets only the objects that are not (!) containers through the pipeline.

-------------------------- EXAMPLE 3 --------------------------

This command gets all the files and directories in the current directory by using Get-ChildItem. It pipes the results to Where-Object, which examines the PSIsContainer property and lets only the objects that are containers through the pipeline.

get-childitem | where-object {$_.psiscontainer}

-------------------------- EXAMPLE 4 --------------------------

This command gets all the files and directories in the current directory by using Get-ChildItem:

get-item -path a | format-list *

It pipes the results to the Where-Object cmdlet, which examines the PSIsContainer property and lets only the objects that are containers through the pipeline.

-------------------------- EXAMPLE 5 --------------------------

This command uses the Get-Item cmdlet to get information about the Test.txt file:

get-item -path test.txt | format-list *

The Format-List cmdlet is used to display all the properties of the resulting object.

Copying Files and Directories

-------------------------- EXAMPLE 1 --------------------------

This command copies the A.txt file from the C:\A directory to the C:\A\Bb directory:

copy-item -path C:\a\a.txt -destination C:\a\bb\a.txt

It overwrites files in the destination directory without prompting for confirmation.

-------------------------- EXAMPLE 2 --------------------------

This command copies all the files in the C:\A\Bb directory that have the .txt file name extension to the C:\A\Cc\Ccc\ directory:

copy-item -path C:\a\bb\*.txt -destination C:\a\cc\ccc\

It uses the original names of the files. The command overwrites the existing files in the destination directory without prompting for confirmation.

-------------------------- EXAMPLE 3 --------------------------

Copies all the directories and files in the C:\a directory to the C:\c directory. If any of the directories to copy already exist in the destination directory, the command will fail unless you specify the Force parameter.

copy-item -path C:\a\* -destination C:\c -recurse

Moving Files and Directories

-------------------------- EXAMPLE 1 --------------------------

This command moves the C.txt file in the C:\A directory to the C:\A\Aa directory:

move-item -path C:\a\c.txt -destination C:\a\aa

The command will not automatically overwrite an existing file that has the same name. To force the cmdlet to overwrite an existing file, specify the Force parameter.

-------------------------- EXAMPLE 2 --------------------------

This command moves the C:\A directory and all its contents to the C:\B directory:

move-item -path C:\a -destination C:\b

You cannot move a directory when that directory is the current location.

Managing File Content

-------------------------- EXAMPLE 1 --------------------------

This command appends the "test content" string to the Test.txt file:

add-content -path test.txt -value "test content"

The existing content in the Test.txt file is not deleted.

-------------------------- EXAMPLE 2 --------------------------

This command gets the contents of the Test.txt file and displays them in the console:

get-content -path test.txt

You can pipe the contents of the file to another cmdlet. For example, the following command reads the contents of the Test.txt file and then supplies them as input to the ConvertTo-HTML cmdlet: get-content -path test.txt | convertto-html

-------------------------- EXAMPLE 3 --------------------------

This command replaces the contents of the Test.txt file with the "test content" string:

set-content -path test.txt -value "test content"

It overwrites the contents of Test.txt. You can use the Value parameter of the New-Item cmdlet to add content to a file when you create it.

Managing Security Descriptors

-------------------------- EXAMPLE 1 --------------------------

This command returns a System.Security.AccessControl.FileSecurity object:

get-acl -path test.txt | format-list -property *

For more information about this object, pipe the command to the Get-Member cmdlet. Or, see "FileSecurity Class" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=145718.

-------------------------- EXAMPLE 2 --------------------------

This command returns a System.Security.AccessControl.DirectorySecurity object:

get-acl -path test_directory | format-list -property *

For more information about this object, pipe the command to the Get-Member cmdlet. Or, see "DirectorySecurity Class" in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=145736.

Creating Files and Directories

-------------------------- EXAMPLE 1 --------------------------

This command creates the Logfiles directory on the C drive:

new-item -path c:\ -name logfiles -type directory

-------------------------- EXAMPLE 2 --------------------------

This command creates the Log2.txt file in the C:\Logfiles directory and then adds the "test log" string to the file:

new-item -path c:\logfiles -name log.txt -type file

-------------------------- EXAMPLE 3 --------------------------

Creates a file called Log2.txt in the C:\logfiles directory and adds the string "test log" to the file.

new-item -path c:\logfiles -name log2.txt -type file -value "test log"

Renaming Files and Directories

-------------------------- EXAMPLE 1 --------------------------

This command renames the A.txt file in the C:\A directory to B.txt:

rename-item -path c:\a\a.txt -newname b.txt

-------------------------- EXAMPLE 2 --------------------------

This command renames the C:\A\Cc directory to C:\A\Dd:

rename-item -path c:\a\cc -newname dd

Deleting Files and Directories

-------------------------- EXAMPLE 1 --------------------------

This command deletes the Test.txt file in the current directory:

remove-item -path test.txt

-------------------------- EXAMPLE 2 --------------------------

This command deletes all the files in the current directory that have the .xml file name extension:

remove-item -path *.xml

Starting a Program by Invoking an Associated File

-------------------------- EXAMPLE 1 --------------------------

The first command uses the Get-Service cmdlet to get information about local services.

It pipes the information to the Export-Csv cmdlet and then stores that information in the Services.csv file.

The second command uses Invoke-Item to open the Services.csv file in the program associated with the .csv extension:

get-service | export-csv -path services.csv

invoke-item -path services.csv

DYNAMIC PARAMETERS

Dynamic parameters are cmdlet parameters that are added by a Windows PowerShell provider and are available only when the cmdlet is being used in the provider-enabled drive.

Encoding <Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding>

Value | Description
Unknown | The encoding type is unknown or invalid. The data can be treated as binary.
String | Uses the encoding type for a string.
Unicode | Encodes in UTF-16 format using the little-endian byte order.
Byte | Encodes a set of characters into a sequence of bytes.
BigEndianUnicode | Encodes in UTF-16 format using the big-endian byte order.
UTF8 | Encodes in UTF-8 format.
UTF7 | Encodes in UTF-7 format.
ASCII | Uses the encoding for the ASCII (7-bit) character set.

Cmdlets supported:

  • Add-Content

  • Get-Content

  • Set-Content

Delimiter <System.String>

Specifies the delimiter to use when reading the file. The default is "\n" (end of line).

Cmdlets supported:

  • Get-Content

Wait <System.Management.Automation.SwitchParameter>

Waits for content to be appended to the file. If content is appended, it returns the appended content. If the content has changed, it returns the entire file.

When waiting, Get-Content checks the file once each second until you interrupt it, such as by pressing CTRL+C.

Cmdlets supported:

  • Get-Content

See Also

  • about_Providers


Function Provider

PROVIDER NAME

Function

DRIVES

Function:

SHORT DESCRIPTION

Provides access to the functions defined in Windows PowerShell.

DETAILED DESCRIPTION

The Windows PowerShell Function Provider lets you get, add, change, clear, and delete the functions and filters in Windows PowerShell.

A function is a named block of code that performs an action. When you type the function name, the code in the function runs. A filter is a named block of code that establishes conditions for an action. You can type the name of the filter in place of the condition, such as in a Where-Object command.

In the Function: drive, functions are preceded by the label "Function" and filters are preceded by the label "Filter", but they operate properly when used in the correct context regardless of the label.

The Function Provider is a flat namespace that contains only the function and filter objects. Neither functions nor filters have child items.

Each function is an instance of the System.Management.Automation.FunctionInfo class. Each filter is an instance of the System.Management.Automation.FilterInfo class.

The examples in this section show how to manage functions, but the same methods can be used with filters.

The Function Provider exposes its data store in the Function: drive. To work with functions, you can change your location to the Function: drive ("set-location function:"). Or, you can work from another Windows PowerShell drive. To reference a function from another location, use the drive name (Function:) in the path.

The Function Provider supports all of the cmdlets whose names contain the Item noun (the Item cmdlets), except for Invoke-Item. And, it supports the Get-Content and Set-Content cmdlets. However, it does not support the cmdlets whose names contain the ItemProperty noun (the ItemProperty cmdlets), and it does not support the Filter parameter in any cmdlet.

All changes to the functions affect the current console only. To save the changes, add the function to the Windows PowerShell profile, or use Export-Console to save the current console.

EXAMPLES

Getting to the Function: Drive

-------------------------- EXAMPLE 1 --------------------------

Changes the current location to the Function: drive. You can use this command from any drive in Windows PowerShell. To return to a file system drive, type the drive name. For example, type "set-location c:".

set-location function:

Getting Functions

-------------------------- EXAMPLE 1 --------------------------

This command gets the list of all the functions in the current session. You can use this command from any Windows PowerShell drive.

get-childitem -path function:

-------------------------- EXAMPLE 2 --------------------------

This command gets the "man" function from the Function: drive. It uses the Get-Item cmdlet to get the function. The pipeline operator (|) sends the result to Format-Table.

The Wrap parameter directs text that does not fit on the line onto the next line. The Autosize parameter resizes the table columns to accommodate the text.

get-item -path man | format-table -wrap -autosize

If you are in a different drive, add the drive name (Function:) to the path.

-------------------------- EXAMPLE 3 --------------------------

These commands both get the function named "c:". The first command can be used in any drive. The second command is used in the Function: drive.

Because the name ends in a colon, which is the syntax for a drive, you must qualify the path with the drive name. Within the Function: drive, you can use either format. In the second command, the dot (.) represents the current location.

c:\PS> get-item -path function:c:

PS Function> get-item -path .\c:

Creating a Function

-------------------------- EXAMPLE 1 --------------------------

This command uses the New-Item cmdlet to create a function called "HKLM:". The expression in braces is the script block that is represented by the function name.

new-item -path function:hklm: -value {set-location hklm:}

You can also create a function by typing it at the Windows PowerShell command line. For example, tpe "function:hklm: {set-location hklm:}". If you are in the Function: drive, you can omit the drive name. Because you cannot specify the "Filter" label in New-Item, filters are labeled as functions, but they operate properly with any label. To create a filter with the "Filter" label, type the filter at the command line. For example, type "filter:Running {$_.Status -eq "Running"}".

-------------------------- EXAMPLE 2 --------------------------

This command uses the New-Item cmdlet to create a function called Csrss. It uses the Options dynamic parameter to specify a value of ReadOnly for the Options property of the function.

new-item -path function: -name csrss -options readonly -value {get-process csrss}

This command works from any location. If you are in the Function: drive, you can use a dot (.) to specify the path. The dot represents the current location.

Deleting a Function

-------------------------- EXAMPLE 1 --------------------------

This command deletes the "hklm:" function from the current session.

remove-item function:hklm:

-------------------------- EXAMPLE 2 --------------------------

This command deletes all the functions from the current session except for the functions whose Options property has a value of Constant. Without the Force parameter, the command does not delete functions whose Options property has a value of ReadOnly.

remove-item function:* -force

When you delete all the functions, the command prompt changes because the prompt function, which defines the content of the command prompt, is deleted.

Displaying the Properties and Methods of Functions

-------------------------- EXAMPLE 1 --------------------------

This command uses the Get-Item cmdlet to get all the functions. The pipeline operator sends the results to the Get-Member cmdlet, which displays the methods and the properties of the object.

get-item -path function:* | get-member

When you pipe a collection of objects (such as the collection of functions in the Function: drive) to Get-Member, Get-Member evaluates each object in the collection separately and returns information about each object type that it finds. If all of the objects are of the same type, it returns information about the single object type. In this case, all of the functions are FunctionInfo objects. To get information about the collection of FunctionInfo objects, use the InputObject parameter of Get-Member. For example, type "get-member -InputObject (get-item function:*)". When you use the InputObject parameter, Get-Member evaluates the collection, not the objects in the collection.

-------------------------- EXAMPLE 2 --------------------------

This command lists the values of the properties of the "prompt" function. It uses the Get-Item cmdlet to get an object that represents the "prompt" function. The pipeline operator (|) sends the results to the Format-List command. The Format-List command uses the Property parameter with a wildcard character (*) to format and to display the values of all of the properties of the "prompt" function.

get-item function:prompt | format-list -property *

Changing the Properties of a Function

-------------------------- EXAMPLE 1 --------------------------

You can use the Set-Item cmdlet with the Options dynamic parameter to change the value of the Options property of a function.

This command sets the AllScope and ReadOnly options for the "prompt" function. This command uses the Options dynamic parameter of the Set-Item cmdlet. The Options parameter is available in Set-Item only when you use it with the Alias or Function provider.

set-item -path function:prompt -options "AllScope,ReadOnly"

-------------------------- EXAMPLE 2 --------------------------

This command uses the Set-Item cmdlet to change the "prompt" function so that it displays the time before the path.

set-item -path function:prompt -value {'PS '+ $(Get-Date -format t) + " " + $(Get-Location) + '> '}

The change affects both the Definition and ScriptBlock properties of the FunctionInfo object. To see the effect of the change, type "get-item -path function:prompt | format-list -property *".

-------------------------- EXAMPLE 3 --------------------------

This command uses the Rename-Item cmdlet to change the name of the "help" function to "gh".

rename-item -path function:help -newname gh

Copying a Function

-------------------------- EXAMPLE 1 --------------------------

This command copies the "prompt" function to "oldPrompt", effectively creating a new name for the script block that is associated with the prompt function. You can use this to save the original prompt function if you plan to change it.

The Options property of the new function has a value of None. To change the value of the Options property, use Set-Item.

copy-item -path function:prompt -destination function:oldPrompt

DYNAMIC PARAMETERS

Dynamic parameters are cmdlet parameters that are added by a Windows PowerShell provider and are available only when the cmdlet is being used in the provider-enabled drive.

Options <System.Management.Automation.ScopedItemOptions>

Determines the value of the Options property of a function.

Value | Description
None | No options. "None" is the default.
Constant | The function cannot be deleted, and its properties cannot be changed. Constant is available only when you are creating a function. You cannot change the option of an existing function to Constant.
Private | The function is visible only in the current scope (not in child scopes).
ReadOnly | The properties of the function cannot be changed except by using the Force parameter. You can use Remove-Item to delete the function.
AllScope | The function is copied to any new scopes that are created.

Cmdlets supported:

  • New-Item

  • Set-Item

See Also

  • about_Functions
  • about_Providers


Registry Provider

PROVIDER NAME

Registry

DRIVES

HKLM:, HKCU:

SHORT DESCRIPTION

Provides access to the system registry keys and values from Windows PowerShell.

DETAILED DESCRIPTION

The Windows PowerShell Registry Provider lets you get, add, change, clear, and delete registry keys and values in Windows PowerShell.

Registry keys are represented as instances of the Microsoft.Win32.RegistryKey class. Registry values are represented as instances of the PSCustomObject class.

The Registry Provider lets you access a hierarchical namespace that consists of registry keys and subkeys. Registry values and data are not components of that hierarchy. Instead, they are properties of each of the keys.

The Registry Provider supports all the cmdlets that contain the Item noun (the Item cmdlets), such as Get-Item, Copy-Item, and Rename Item. Use the Item cmdlets when you work with registry keys and subkeys. The Registry Provider also supports the cmdlets that contain the ItemProperty noun (the ItemProperty cmdlets). Use the ItemProperty cmdlets when you work with registry values and data. You cannot use the cmdlets that contain the Content noun (the Content cmdlets) with the Registry Provider.

Each registry key is protected by a security descriptor. You can use Get-Acl to view the security descriptor of a key.

CAPABILITIES

ShouldProcess

EXAMPLES

Navigating the Registry

-------------------------- EXAMPLE 1 --------------------------

This command sets the current location to the HKEY_LOCAL_MACHINE\Software registry key:

set-location hklm:\software

-------------------------- EXAMPLE 2 --------------------------

This command displays the current location:

get-location

Managing Registry Keys

-------------------------- EXAMPLE 1 --------------------------

This command displays information about each immediate subkey of the HKEY_LOCAL_MACHINE\Software registry key:

get-childitem -path hklm:\software

-------------------------- EXAMPLE 2 --------------------------

This command creates the TestNew subkey under the HKCU:\Environment subkey:

new-item -path hkcu:\Environment\TestNew

-------------------------- EXAMPLE 3 --------------------------

This command removes the TestNew subkey of the HKEY_CURRENT_USER\Environment key:

remove-item -path hkcu:\Environment\TestNew

-------------------------- EXAMPLE 4 --------------------------

This command copies the TestNew key to the TestCopy subkey:

copy-item -path  hkcu:\Environment\TestNew  hkcu:\Environment\TestNew\TestCopy

-------------------------- EXAMPLE 5 --------------------------

This command displays information about all the subkeys of the HKEY_LOCAL_MACHINE\Software registry key:

get-childitem -path hklm:\Software -recurse

-------------------------- EXAMPLE 6 --------------------------

This command moves the HKEY_CURRENT_USER\Environment\testnewcopy registry key, its properties, and all its subkeys and their properties to HKEY_CURRENT_USER\Environment\testnew:

move-item -path hkcu:\environment\testnewcopy `
-destination hkcu:\environment\testnew

-------------------------- EXAMPLE 7 --------------------------

This command renames the HKEY_CURRENT_USER\Environment\testnew registry key to HKEY_CURRENT_USER\Environment\test:

rename-item -path hkcu:\environment\testnew\ -newname test

-------------------------- EXAMPLE 8 --------------------------

This command displays the security descriptor for the specified registry item:

get-acl -path hkcu:\environment\testnew | format-list -property *

Managing Registry Entries

-------------------------- EXAMPLE 1 --------------------------

This command displays the value name and value data for each registry entry in the HKEY_CURRENT_USER\Environment registry key:

get-itemproperty -path hkcu:\Environment

The Default registry entry is returned only if it has a value.

-------------------------- EXAMPLE 2 --------------------------

This command displays the value name and value data for the Temp registry entry in the HKEY_CURRENT_USER\Environment registry key:

get-itemproperty -path hkcu:\Environment -name Temp

-------------------------- EXAMPLE 3 --------------------------

This command creates the pstest registry entry in the HKEY_CURRENT_USER key and sets its value to pstestvalue:

new-itemproperty -path hkcu:\environment -name "pstest" -value "pstestvalue"

-------------------------- EXAMPLE 4 --------------------------

This command updates the value of the pstest registry entry to updatedvalue in the HKEY_CURRENT_USER\Environment key:

set-itemproperty -path hkcu:\environment -name pstest
-value "updatedvalue"

-------------------------- EXAMPLE 5 --------------------------

This command renames the value name of the pstest registry entry to pstestnew in the HKEY_CURRENT_USER\Environment key:

rename-itemproperty -path hkcu:\environment -name pstest `
-newname pstestnew

-------------------------- EXAMPLE 6 --------------------------

This command copies the pstestnew registry entry from the HKEY_CURRENT_USER\Environment key to the HKEY_CURRENT_USER\Environment\testnewcopy key:

copy-itemproperty -path hkcu:\environment `
-destination hkcu:\environment\testnewcopy -name pstestnew

-------------------------- EXAMPLE 7 --------------------------

The command moves the pstestnew registry entry from the HKEY_CURRENT_USER\environment\testnewcopy key to the HKEY_CURRENT_USER\environment\testnew key:

move-itemproperty -path hkcu:\environment\testnewcopy '
-destination hkcu:\environment\testnew -name pstestnew

-------------------------- EXAMPLE 8 --------------------------

This command clears the value of the pstestnew registry entry in the HKEY_CURRENT_USER\Environment\testnew key:

clear-itemproperty -path hkcu:\environment\testnew -name pstestnew

You can use the Clear-Item cmdlet to clear the value of the default registry entry for a subkey. For example, the following command clears the value of the default entry of the HKEY_CURRENT_USER\Environment\testnew registry key: clear-item -path hkcu:\environment\testnew

-------------------------- EXAMPLE 9 --------------------------

This command removes the pstestnew registry entry from the HKEY_CURRENT_USER\Environment\testnew registry key:

remove-itemproperty -path hkcu:\environment\testnew `
-name pstestnew

-------------------------- EXAMPLE 10 --------------------------

This command updates the value of the default registry entry in the HKEY_CURRENT_USER\Environment\testnew key to "default value":

set-itemproperty -path hkcu:\environment\testnew `
-name "(default)" -value "default value"

You can also update the default value of a registry key by using the Set-Item cmdlet. For example, the following command updates the default value of the testnew key: set-item -path hkcu:\environment\testnew -value "another default value"

DYNAMIC PARAMETERS

Dynamic parameters are cmdlet parameters that are added by a Windows PowerShell provider and are available only when the cmdlet is being used in the provider-enabled drive.

Type <Microsoft.Win32.RegistryValueKind>

Specifies the data types to use when storing values in the registry, or identifies the data type of a value in the registry.

Value | Description
String | Specifies a null-terminated string. Equivalent to REG_SZ.
ExpandString | Specifies a null-terminated string that contains unexpanded references to environment variables that are expanded when the value is retrieved. Equivalent to REG_EXPAND_SZ.
Binary | Specifies binary data in any form. Equivalent to REG_BINARY.
DWord | Specifies a 32-bit binary number. Equivalent to REG_DWORD.
MultiString | Specifies an array of null-terminated strings terminated by two null characters. Equivalent to REG_MULTI_SZ.
QWord | Specifies a 64-bit binary number. Equivalent to REG_QWORD.
Unknown | Indicates an unsupported registry data type, such as REG_RESOURCE_LIST.

Cmdlets supported:

  • Set-Item

See Also

  • about_Providers


Variable Provider

PROVIDER NAME

Variable

DRIVES

Variable:

SHORT DESCRIPTION

Provides access to the Windows PowerShell variables and to their values.

DETAILED DESCRIPTION

The Windows PowerShell Variable Provider lets you get, add, change, clear, and delete Windows PowerShell variables in the current console.

The Windows PowerShell Variable Provider supports the variables that Windows PowerShell creates, including the automatic variables, the preference variables, and the variables that you create.

The Variable Provider is a flat namespace that contains only the variable objects. The variables have no child items.

Most of the variables are instances of the System.Management.Automation.PSVariable class. However, there are some variations. For example, the "?" variable is a member of the QuestionMarkVariable class, and the "MaximumVariableCount" variable is a member of the SessionStateCapacityVariable class.

The Variable Provider exposes its data store in the Variable: drive. To work with variables, you can change your location to the Variable: drive ("set-location variable:"), or you can work from any other Windows PowerShell drive. To reference a variable from another location, use the drive name (Variable:) in the path.

Windows PowerShell includes a set of cmdlets designed especially to view and to change variables:

-- Get-Variable

-- New-Variable

-- Set-Variable

-- Remove-Variable

-- Clear-Variable

When you use these cmdlets, you do not need to specify the Variable: drive in the name.

The Variable Provider supports all of the cmdlets whose names contain the Item noun (the Item cmdlets), except for Invoke-Item. The Variable Provider supports the Get-Content and Set-Content cmdlets. However, it does not support the cmdlets whose names contain the ItemProperty noun (the ItemProperty cmdlets), and it does not support the Filter parameter in any cmdlet.

You can also use the Windows PowerShell expression parser to create, view, and change the values of variables without using the cmdlets. When working with variables directly, use a dollar sign ($) to identify the name as a variable and the assignment operator (=) to establish and change its value. For example, "$p = Get-Process" creates the "p" variable and stores the results of a "Get-Process" command in it.

All changes to the variables affect the current session only. To save the changes, add the changes to the Windows PowerShell profile, or use Export-Console to save the current console.

EXAMPLES

Getting to the Variable: Drive

-------------------------- EXAMPLE 1 --------------------------

This command changes the current location to the Variable: drive. You can use this command from any drive in Windows PowerShell. To return to a file system drive, type the drive name. For example, type "set-location c:".

set-location variable:

Displaying the Value of Variables

-------------------------- EXAMPLE 1 --------------------------

This command gets the list of all the variables and their values in the current session. You can use this command from any Windows PowerShell drive.

get-childitem -path variable:

-------------------------- EXAMPLE 2 --------------------------

This command gets the variables with names that begin with "max". You can use this command from any Windows PowerShell drive.

get-childitem -path variable:max*

If you are in the Variable: drive, you can omit the drive name from the path.

-------------------------- EXAMPLE 3 --------------------------

This command gets the value of the WhatIfPreference variable by typing it at the command line.

The name of the variable is preceded by a dollar sign ($) to indicate that it is a variable. The Variable: drive name is not specified.

$WhatIfPreference

-------------------------- EXAMPLE 4 --------------------------

This command uses the LiteralPath parameter of Get-ChildItem to get the value of the "?" variable from within the Variable: drive. Get-ChildItem does not attempt to resolve any wildcards in the values of the LiteralPath parameter.

get-childitem -literalpath ?

To display the value of a variable with a special character name without a cmdlet, type a dollar sign ($) and the variable name. For example, to display the value of the "?" variable, type "$?".

-------------------------- EXAMPLE 5 --------------------------

This command gets the variables that have the values of "ReadOnly" or "Constant" for their Options property.

get-childitem -path variable: | where-object {$_.options -match "Constant" -or $_.options -match "ReadOnly"} | format-list -property name, value, options

Creating a New Variable

-------------------------- EXAMPLE 1 --------------------------

This command creates the "services" variable and stores the results of a Get-Service command in it. Because the current location is in the Variable: drive, the value of the Path parameter is a dot (.), which represents the current location.

The parentheses around the Get-Service command ensure that the command is executed before the variable is created. Without the parentheses, the value of the new variable is a "Get-Service" string.

new-item -path . -name services -value (Get-Service)

If you are not in the variable: drive, include the Variable: drive name in the path.

-------------------------- EXAMPLE 2 --------------------------

This command creates a "services" variable and stores the result of a Get-Service command in it.

The command uses a dollar sign ($) to indicate a variable and the assignment operator (=) to assign the result of the Get-Service command to the newly created variable.

$services = Get-Service

To create a variable without a value, omit the assignment operator.

Displaying the Properties and Methods of Variables

-------------------------- EXAMPLE 1 --------------------------

This command uses the Get-Item cmdlet to get all variables. The pipeline operator (|) sends the results to the Get-Member cmdlet, which displays the methods and properties of the object.

get-item -path variable:* | get-member

When you pipe a collection of objects (such as the collection of variables in the Variable: drive) to Get-Member, Get-Member evaluates each object in the collection separately and returns information about each of the object types that it finds. To get information about the collection of objects in the Variable: drive, use the InputObject parameter of Get-Member. For example, "get-member -inputobject (get-item variable:*)". When you use InputObject, Get-Member evaluates the collection, not the objects in the collection.

-------------------------- EXAMPLE 2 --------------------------

This command lists the values of the properties of the "home" variable. It uses the Get-Item cmdlet to get an object that represents the "home" variable. The pipeline operator (|) sends the results to the Format-List command. The Format-List command uses the Property parameter with a wildcard character (*) to format and to display the values of all of the properties of the "home" variable.

get-item variable:home | format-list -property *

Changing the Properties of a Variable

-------------------------- EXAMPLE 1 --------------------------

This command uses the Rename-Item cmdlet to change the name of the "a" variable to "processes".

rename-item -path variable:a -newname processes

-------------------------- EXAMPLE 2 --------------------------

This command uses the Set-Item cmdlet to change the value of the ErrorActionPreference variable to "Stop".

set-item -path variable:ErrorActionPreference -value Stop

-------------------------- EXAMPLE 3 --------------------------

This command changes the value of the ErrorActionPreference variable to "Stop".

It uses a dollar sign ($) to indicate a variable and the assignment operator (=) to assign the value.

$ErrorActionPreference = Stop

Copying a Variable

-------------------------- EXAMPLE 1 --------------------------

This command uses the Copy-Item cmdlet to copy the "processes" variable to "old_processes". This creates a new variable named "old_processes" that has the same value as the "processes" variable.

copy-item -path variable:processes -destination variable:old_processes

If the command is issued from within the Variable: drive, you can omit the drive name from the value of the Path parameter.

-------------------------- EXAMPLE 2 --------------------------

This command copies the "processes" variable to "old_processes" without using a cmdlet. It uses the dollar sign ($) to indicate variables and the assignment operator to assign the value of $processes to old_processes.

$old_processes = $processes

Deleting a Variable

-------------------------- EXAMPLE 1 --------------------------

This command deletes the "serv" variable from the current session. You can use this command in any Windows PowerShell drive.

remove-variable -path variable:serv

-------------------------- EXAMPLE 2 --------------------------

This command deletes all variables from the current session except for the variables whose Options property has a value of Constant. Without the Force parameter, the command does not delete variables whose Options property has a value of ReadOnly.

remove-item variable:* -force

Setting the Value of a Variable to NULL

-------------------------- EXAMPLE 1 --------------------------

This command uses the Clear-Item cmdlet to change the value of the "processes" variable to NULL.

clear-item -path variable:processes

-------------------------- EXAMPLE 2 --------------------------

This command clears the value of the "processes" variable by assigning a null value to it. It uses the $null automatic variable to represent the NULL value.

$processes = $null

See Also

  • about_Variables
  • about_Automatic_Variables
  • about_Providers


WS-Management Provider

PROVIDER NAME

WS-Management

DRIVES

WSMan

SHORT DESCRIPTION

Provides access to Web Services for Management (WS-Management) configuration information.

DETAILED DESCRIPTION

The WS-Management provider for Windows PowerShell lets you add, change, clear, and delete WS-Management configuration data on local or remote computers.

The WS-Management provider exposes a Windows PowerShell drive with a directory structure that corresponds to a logical grouping of WS-Management configuration settings. These groupings are known as containers.

-- Client

You can configure various aspects of the WS-Management client. The configuration information is stored in the registry.

-- Service

You can configure various aspects of the WS-Management service. The configuration information is stored in the registry.

Note: Service configuration is sometimes referred to as Server configuration.

-- Shell

You can configure various aspects of the WS-Management shell, such as the setting to allow remote shell access (AllowRemoteShellAccess) and the maximum number of concurrent users allowed (MaxConcurrentUsers).

-- Listener

You can create and configure a listener. A listener is a management service that implements the WS-Management protocol to send and to receive messages.

-- Plugin

Plug-ins are loaded and used by the WS-Management service to provide various functions. By default, Windows PowerShell provides three plug-ins: the Event Forwarding plug-in, the Microsoft.PowerShell plug-in, and the Windows Management Instrumentation (WMI) Provider plug-in. These three plug-ins support event forwarding, configuration, and WMI access.

-- ClientCertificate

You can create and configure a client certificate. A client certificate is used when the WS-Management client is configured to use certificate authentication.

Directory Hierarchy of the WS-Management Provider

---------------

The directory hierarchy of the WS-Management provider for the local computer is as follows:

WSMan:\localhost

--- Client

--- Service

--- Shell

--- Listener

------ <Specific_Listener>

--- Plugin

------ Event Forwarding Plugin

--------- InitializationParameters

--------- Resources

------------ Security

------ Microsoft.Powershell

--------- InitializationParameters

--------- Resources

------------ Security

------ WMI Provider

--------- InitializationParameters

--------- Resources

------------ Security

--- ClientCertificate

The directory hierarchy of the WS-Management provider for a remote computer is the same as a local computer. However, in order to access the configuration settings of a remote computer, you need to make a connection to the remote computer using Connect-WSMan. Once a connection is made to a remote computer, the name of the remote computer shows up in the provider.

WSMan:\<Remote_Computer_Name>

--- Client

--- Service

--- Shell

--- Listener

------ <Specific_Listener>

--- Plugin

------ Event Forwarding Plugin

--------- InitializationParameters

--------- Resources

------------ Security

------ Microsoft.Powershell

--------- InitializationParameters

--------- Resources

------------ Security

------ WMI Provider

--------- InitializationParameters

--------- Resources

------------ Security

--- ClientCertificate

Custom Provider Help

--------------------

The Listener, Plugin (IntitializationParameters, Resources, Security) and ClientCertificate provider paths provide specific New-Item support. Type "Get-Help New-Item" in the relevant path for custom help.

EXAMPLES

Navigating the WSMan: Drive

-------------------------- EXAMPLE 1 --------------------------

This command uses the Set-Location cmdlet to change the current location to the WSMan: drive.

Set-Location WSMan:

-------------------------- EXAMPLE 2 --------------------------

This command uses the Set-Location command to change the current location to the root location in the Localhost store location. Use a backslash (\) or forward slash (/) to indicate a level of the WSMan: drive.

Set-Location -Path Localhost

If you are not in the WSMan: drive, begin the path with the drive name.

-------------------------- EXAMPLE 3 --------------------------

This command uses the Set-Location command to change the current location to the root location in the remote system store location. Use a backslash (\) or forward slash (/) to indicate a level of the WSMan: drive.

Set-Location -Path  WSMan:\SERVER01

If you are not in the WSMan: drive, begin the path with the drive name. The above command assume that a connection to the remote system already exists. If a connection has not been made to the remote system, then a connection could be make immediately prior to navigating to the root location in the remote system store location. For example: WSMan-Connect SERVER01 Set-Location -Path WSMan:\SERVER01

-------------------------- EXAMPLE 4 --------------------------

This command uses the Set-Location command to change the current location to the Client location in the Localhost store location. Use a backslash (\) or forward slash (/) to indicate a level of the WSMan: drive.

Set-Location -Path Localhost\Client

If you are not in the WSMan: drive, begin the path with the drive name.

Displaying the Contents of the WSMan: Drive

-------------------------- EXAMPLE 1 --------------------------

This command uses the Get-Childitem cmdlet to display the WS-Management stores in the Localhost store location.

get-childitem -path WSMan:\Localhost

If you are in the WSMan: drive, you can omit the drive name.

-------------------------- EXAMPLE 2 --------------------------

This command uses the Get-Childitem cmdlet to display the WS-Management stores in the remote computer (SERVER01) store location.

get-childitem -path WSMan:\SERVER01

If you are in the WSMan: drive, you can omit the drive name. The above command assume that a connection to the remote system already exists. If a connection has not been made to the remote system, then a connection could be make immediately displaying the properties and containers in the remote system store location. For example: WSMan-Connect SERVER01 get-childitem -path WSMan:\SERVER01

-------------------------- EXAMPLE 3 --------------------------

This command uses the Get-Childitem cmdlet to display the current WS-Management connections.

get-childitem -path WSMan:\

If you are in the WSMan: drive, you can omit the drive name.

-------------------------- EXAMPLE 4 --------------------------

This command uses the Get-Item cmdlet to get the properties and containers in the current store.

Get-Childitem

The above command returns a list of properties and containers. For example: PS WSMan:\localhost&gt; get-childitem WSManConfig: Microsoft.WSMan.Management\WSMan::localhost Name Value Type ---- ----- ---- MaxEnvelopeSizekb 150 System.String MaxTimeoutms 60000 System.String MaxBatchItems 32000 System.String MaxProviderRequests 4294967295 System.String Client Container Service Container Shell Container Listener Container Plugin Container ClientCertificate Container

DYNAMIC PARAMETERS

Dynamic parameters are cmdlet parameters that are added by a Windows PowerShell provider and are available only when the cmdlet is being used in the provider-enabled drive.

Address <String>

Specifies the address for which this listener was created. The value can be one of the following:

-- The literal string "*". (The wildcard character (*) makes the command bind all the IP addresses on all the network interface cards [NIC].)

-- The literal string "IP:" followed by a valid IP address in either IPv4 dotted-decimal format or in IPv6 cloned-hexadecimal format.

-- The literal string "MAC:" followed by the MAC address of a NIC. For example: MAC:32-a3-58-90-be-cc.

Note: The Address value is set when creating a Listener.

Cmdlets supported:

  • Get-Item

AllowRemoteShellAccess <Boolean>

Enables access to remote shells. If you set this parameter to False, new remote shell connections will be rejected by the server. The default is True.

Cmdlets supported:

  • Get-Item

  • Set-Item

AllowUnEncrypted <Boolean>

Allows the client computer to request unencrypted traffic. By default, the client computer requires encrypted network traffic.

Cmdlets supported:

  • Get-Item

  • Set-Item

Arguments <String>

Specifies the argument string and the command-line arguments that you want to pass to the custom shell. This parameter is optional.

Cmdlets supported:

  • Get-Item

  • Set-Item

Basic <Boolean>

Allows the client computer to use Basic authentication. Basic authentication is a scheme in which the user name and password are sent in clear text to the server or proxy. This method is the least secure method of authentication.

Cmdlets supported:

  • Get-Item

  • Set-Item

Capability <Enumeration>

Specifies an operation that is supported on this Uniform Resource Identifier (URI). You have to create one entry for each type of operation that the URI supports. The following are valid values:

-- Create: Create operations are supported on the URI. The SupportFragment attribute is used if the Create operation supports the concept. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if Shell operations are also supported.

-- Delete: Delete operations are supported on the URI. The SupportFragment attribute is used if the Delete operation supports the concept. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if Shell operations are also supported.

-- Enumerate: Enumerate operations are supported on the URI. The SupportFragment attribute is not supported for Enumerate operations and should be set to False. The SupportFiltering attribute is valid, and if the plug-in supports filtering, this attribute should be set to True. This operation is not valid for a URI if Shell operations are also supported.

-- Get: Get operations are supported on the URI. The SupportFragment attribute is used if the Get operation supports the concept. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if Shell operations are also supported.

-- Invoke: Invoke operations are supported on the URI. The SupportFragment attribute is not supported for Invoke operations and should be set to False. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if Shell operations are also supported.

-- Put: Put operations are supported on the URI. The SupportFragment attribute is used if the Put operation supports the concept. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if Shell operations are also supported.

-- Subscribe: Subscribe operations are supported on the URI. The SupportFragment attribute is not supported for Subscribe operations and should be set to False. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if Shell operations are also supported.

-- Shell: Shell operations are supported on the URI. The SupportFragment attribute is not supported for Shell operations and should be set to False. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if any other operation is also supported. If a Shell operation is configured for a URI, Get, Put, Create, Delete, Invoke, and Enumerate operations are processed internally within the WS-Management (WinRM) service to manage shells. As a result, the plug-in cannot handle the operations.

Cmdlets supported:

  • Get-Item

  • New-Item

  • Remove-Item

  • Set-Item

CbtHardeningLevel <String>

Sets the policy for channel-binding token requirements in authentication requests. The following are valid values:

-- Strict: Any request will be denied unless a channel-binding token is present. This setting guarantees that all connections are secured by the use of channel-binding tokens.

-- Relaxed: If a channel-binding token is present in a request, the connection will be secured. If a channel-binding token is not present, the connection will still be accepted. However, it will be vulnerable to attacks that are prevented by the use of channel-binding tokens.

-- None: Any channel-binding tokens that are supplied are ignored.

The value of this parameter is only effective for HTTPS connections.

Cmdlets supported:

  • Get-Item

  • Set-Item

CertificateThumbprint <String>

Specifies the thumbprint of the service certificate.

This value represents the string of two-digit hexadecimal values in the Thumbprint field of the certificate. It specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts, and they do not work with domain accounts. To get a certificate thumbprint, use the Get-Item or Get-ChildItem cmdlets in the Windows PowerShell Cert: drive.

Cmdlets supported:

  • Clear-Item

  • Get-Item

  • Set-Item

Certificate <Boolean>

Allows the client to be used for certificate authentication. The WS-Management client will try to find the certificate in the computer store. If the client cannot find the certificate in the computer store, the client tries to find it in the current user store. If no matching certificate is found, the user receives an error message.

Cmdlets supported:

  • Get-Item

  • Set-Item

CredSSP <Boolean>

Allows the client to use Credential Security Service Provider (CredSSP) authentication.

CredSSP authentication allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

Caution: CredSSP authentication delegates the user's credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

Cmdlets supported:

  • Get-Item

  • Set-Item

HTTP <Unsigned Short Integer>

Specifies the port that the client will use when HTTP is used. By default, HTTP uses port 80. You can specify any value from 1 through 65535.

Cmdlets supported:

  • Get-Item

  • Set-Item

HTTPS <Unsigned Short Integer>

Specifies the port that the client will use when HTTPS is used. By default, HTTPS uses port 443. You can specify any value from 1 through 65535.

Cmdlets supported:

  • Get-Item

  • Set-Item

Digest <Boolean>

Allows the client to use Digest authentication. Digest authentication is a challenge-response scheme that uses a server-specified data string for the challenge. Only the client computer can initiate a Digest authentication request. The client computer sends a request to the server to authenticate and receives a token string from the server. Then, the client computer sends the resource request, including the user name and a cryptographic hash of the password combined with the token string. Digest authentication is supported for HTTP and for HTTPS. WinRM Shell client scripts and applications can specify Digest authentication, but the WS-Management service does not accept Digest authentication.

Note: Digest authentication over HTTP is not considered secure.

Cmdlets supported:

  • Get-Item

  • Set-Item

Enabled <Boolean>

Specifies whether the listener is enabled or disabled. The default is True.

Cmdlets supported:

  • Get-Item

  • Set-Item

ExactMatch <Boolean>

Specifies how to use the security settings that are specified in the Sddl parameter. If the ExactMatch parameter is set to True, the security settings in Sddl are used only to authorize access attempts to the URI exactly as specified by the URI. If ExactMatch is set to false, the security settings in Sddl are used to authorize access attempts to the URIs that begin with the string specified in the URI.

Cmdlets supported:

  • Get-Item

  • Set-Item

FileName <String>

Specifies an input file to use to update the management resource specified by the ResourceURI and SelectorSet.

Cmdlets supported:

  • Get-Item

  • Set-Item

FileName (Plugin) <String>

Specifies the file name of the operations plug-in. Any environment variables that are put in this entry will be expanded in the users' context when a request is received. Because each user could have a different version of the same environment variable, each user could have a different plug-in. This entry cannot be blank and must point to a valid plug-in.

Cmdlets supported:

  • Get-Item

  • Set-Item

HostName <String>

Specifies the host name of the computer on which the WS-Management (WinRM) service is running.

The value must be a fully qualified domain name, an IPv4 or IPv6 literal string, or a wildcard character.

Cmdlets supported:

  • Clear-Item

  • Get-Item

  • Set-Item

IdleTimeOut <Unsigned Long Integer>

Specifies the maximum time, in milliseconds, that the remote shell will remain open when there is no user activity in the remote shell. The remote shell is automatically deleted after the time that is specified. You can specify any values from 0 through 2147483647. A value of 0 indicates an infinite time-out. The default is 900000 (15 minutes).

Cmdlets supported:

  • Get-Item

  • Set-Item

IPv4Filter <String>

Specifies the IPv4 addresses that listeners can use. The following are valid values:

-- If you leave the parameter blank, no IPv4 addresses can be used.

-- If you enter a wildcard character (*), any IPv4 address can be used.

-- If you enter a list of IP ranges, any IP address in the specified ranges can be used. Separate the ranges by using a comma (,), and specify each range as a pair of IPv4 addresses in dotted-decimal format, separated by a hyphen (-). Make sure that the smaller value occurs first in the pair. The ranges are inclusive.

Note: An IPv4 literal string consists of four dotted decimal numbers, each in the range 0 though 255. For example: 192.168.0.0.

Cmdlets supported:

  • Clear-Item

  • Get-Item

  • Set-Item

IPv6Filter <String>

Specifies the IPv6 addresses that listeners can use. The following are valid values:

-- If you leave the parameter blank, no IPv6 addresses can be used.

-- If you enter a wildcard character (*), any IPv6 address can be used.

-- If you enter a list of IP ranges, any IP address in the specified ranges can be used. Separate the ranges by using a comma (,"), and specify each range as a pair of IPv6 addresses in cloned-hexadecimal format, separated by a hyphen (-). Make sure that the smaller value occurs first in the pair. The ranges are inclusive.

Note: An IPv6 literal string is enclosed in brackets and contains hexadecimal numbers that are separated by colons. For example: [::1] or [3ffe:ffff::6ECB:0101].

Cmdlets supported:

  • Clear-Item

  • Get-Item

  • Set-Item

Issuer <String>

Specifies the name of the certification authority that issued the certificate.

Cmdlets supported:

  • Get-Item

  • Set-Item

Kerberos <Boolean>

Allows the client to use Kerberos authentication. Kerberos authentication is a scheme in which the client and server mutually authenticate by using Kerberos certificates.

Cmdlets supported:

  • Get-Item

  • Set-Item

ListeningOn <String>

Specifies the IP address or all the IP addresses on which the service is actually listening. This is derived from the Address element based upon the actual IPs associated with the listener. The value of the IP address must be in IPv4 dotted-decimal notation or in IPv6 colon-delimited hexadecimal notation. Multiple ListeningOn entries exist, each entry starting with ListeningOn_. For example:

ListeningOn_1201550598

ListeningOn_1973755898

ListeningOn_1508953035

ListeningOn_1560839940

Cmdlets supported:

  • Get-Item

MaxBatchItems <Unsigned Long Integer>

Specifies the maximum number of elements that can be used in a Pull response. You can specify any value from 1 through 4294967295.

Cmdlets supported:

  • Get-Item

  • Set-Item

MaxConcurrentUsers <Unsigned Long Integer>

Specifies the maximum number of users who can concurrently perform remote operations on the same computer through a remote shell. New shell connections will be rejected if they exceed the specified limit. You can specify any value from 1 through 100.

Cmdlets supported:

  • Get-Item

  • Set-Item

MaxEnvelopeSizekb <Unsigned Long Integer>

Specifies the maximum SOAP data in kilobytes. You can specify any value from 32 through 4294967295.

Cmdlets supported:

  • Get-Item

  • Set-Item

MaxMemoryPerShellMB <Unsigned Long Integer>

Specifies the maximum total amount of memory that can be allocated by an active remote shell and all its child processes. You can specify any value from 0 through 2147483647. A value of 0 means that the ability of the remote operations to allocate memory is limited only by the available virtual memory. The default value is 0.

Cmdlets supported:

  • Get-Item

  • Set-Item

MaxProcessesPerShell <Unsigned Long Integer>

Specifies the maximum number of processes that any shell operation is allowed to start. You can specify any number from 0 through 2147483647. A value of 0 allows for an unlimited number of processes. By default, the limit is five processes per shell.

Cmdlets supported:

  • Get-Item

  • Set-Item

MaxProviderRequests <Unsigned Long Integer>

Specifies the maximum number of concurrent requests that are allowed by the service. You can specify any value from 1 through 4294967295. The limit is applied per provider.

Note: This value is deprecated and should not be used.

Cmdlets supported:

  • Get-Item

MaxShellsPerUser <Unsigned Long Integer>

Specifies the maximum number of concurrent shells that any user can remotely open on the same system. If this policy setting is enabled, the user will not be able to open new remote shells if the count exceeds the specified limit. If this policy setting is disabled or is not configured, by default, the limit will be set to two remote shells per user. You can specify any number from 0 through 2147483647. A value of 0 allows for an unlimited number of shells.

Cmdlets supported:

  • Get-Item

  • Set-Item

MaxTimeoutMs <Unsigned Long Integer>

Specifies the maximum time-out in milliseconds that can be used for any request except for Pull requests. You can specify any number from 500 to 4294967295.

Cmdlets supported:

  • Get-Item

  • Set-Item

Name <String>

Specifies a display name for the WS-Management session . You can use the name to refer to the session when using other cmdlets, such as Get-PSSession and Enter-PSSession. The name does not have to be unique to the computer or to the current session.

Cmdlets supported:

  • Get-Item

  • Set-Item

Name (Plugin) <String>

Specifies the display name to use for the plug-in. If an error is returned by the plug-in, the display name will be put in the error XML that is returned to the client application. The name is not locale specific.

Cmdlets supported:

  • Get-Item

  • Set-Item

Negotiate <Boolean>

Allows the client to use Negotiate authentication. Negotiate authentication is a scheme in which the client sends a request to the server to authenticate. The server determines whether to use the Kerberos protocol or NTLM. The Kerberos protocol is selected to authenticate a domain account, and NTLM is selected for local computer accounts. The user name must be specified in the domain\user_name form for a domain user. The user name must be specified in the server_name\user_name format for a local user on a server computer.

Cmdlets supported:

  • Get-Item

  • Set-Item

NetworkDelayMs <Unsigned Long Integer>

Specifies the extra time in milliseconds that the client computer waits to accommodate for network delay time. You can specify any value from 500 through 4294967295.

Cmdlets supported:

  • Get-Item

  • Set-Item

Password <String>

Specifies the password for a local or a domain account. It cannot be NULL.

The client computer can specify the credentials to use when creating a shell on a computer. The user name must be specified in the domain\user_name form for a domain user. The user name must be specified in the server_name\user_name format for a local user on a server computer.

If you use this structure, then it should have both the user name and password fields specified. It can be used with Basic, Digest, Negotiate, or Kerberos authentication. The client must explicitly specify the credentials when either Basic or Digest authentication is used.

Cmdlets supported:

  • Get-Item

  • Set-Item

Plugin <>

WS-Management plug-ins are native dynamic link libraries (DLLs) that plug in to and extend the functionality of WS-Management . The WSW-Management Plug-in API provides functionality that enables a user to write plug-ins by implementing certain APIs for supported resource URIs and operations. After the plug-ins are configured for either the WS-Management (WinRM) service or for Internet Information Services (IIS), the plug-ins are loaded in the WS-Management host or in the IIS host, respectively. Remote requests are routed to these plug-in entry points to perform operations.

Cmdlets supported:

  • New-Item

  • Remove-Item

Port <Unsigned Short Integer>

Specifies the TCP port for which this listener is created. You can specify any value from 1 through 65535.

Cmdlets supported:

  • Get-Item

  • Set-Item

Resource <String>

Specifies an endpoint that represents a distinct type of management operation or value. A service exposes one or more resources, and some resources can have more than one instance. A management resource is similar to a WMI class or to a database table, and an instance is similar to an instance of the class or to a row in the table. For example, the Win32_LogicalDisk class represents a resource. Win32_LogicalDisk="C:\" is a specific instance of the resource.

A Uniform Resource Identifier (URI) contains a prefix and a path to a resource. For example:

http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk

http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

Cmdlets supported:

  • Get-Item

  • Set-Item

ResourceURI <String>

Specifies the Uniform Resource Identifier (URI) that identifies a specific type of resource, such as a disk or a process, on a computer.

A URI consists of a prefix and a path to a resource. For example:

http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk

http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

Cmdlets supported:

  • Get-Item

RootSDDL <String>

Specifies the Security Descriptor Definition Language (SDDL) for the access control entry. This identifies the security settings that are used to authorize access to a specified resource URI.

Cmdlets supported:

  • Get-Item

  • Set-Item

SDKVersion <String>

Specifies the version of the WS-Management plug-in SDK. The only valid value is 1.

Cmdlets supported:

  • Get-Item

  • Set-Item

Shell <String>

Specifies the process string for the custom shell. You can specify environment variables.

Cmdlets supported:

  • Get-Item

  • Set-Item

ShellTimeout <Unsigned Long Integer>

Specifies the length of time before the shell times out due to inactivity. Specify the time-out value in milliseconds.

Cmdlets supported:

  • Get-Item

  • Set-Item

Subject <String>

Specifies the entity that is identified by the certificate.

Cmdlets supported:

  • Get-Item

SupportsOptions <Boolean>

Specifies whether the plug-in supports the use of options, which are passed within the wsman:OptionSet header in a request message.

Cmdlets supported:

  • Get-Item

  • Set-Item

Transport <String>

Specifies the transport to use to send and receive WS-Management protocol requests and responses. The value must be either HTTP or HTTPS.

Note: The Transport value is set when creating a Listener.

Cmdlets supported:

  • Get-Item

TrustedHosts <String>

List of remote computers that are connected to the local computer through a trusted network connection. Requests are allowed to be sent to computers specified in this list when using an authentication scheme and transport that does not allow the client to authenticate the service, such as Basic authentication over HTTP.

If a server is specified in TrustedHosts, the client does not authenticate the server's identity, leaving it vulnerable to man-in-the-middle attacks. You should only specify hostnames when the network connection is safe from malicious users, such as in a Domain environment.

The specified host names can be either Domain Name System (DNS) names or IP addresses. The following values are valid:

-- Blank: No hosts are trusted.

-- The asterisk "*" character: All hosts are trusted.

A list of host name patterns separated by commas (,) The host name patterns must be formatted as follows:

-- A string that starts with the wildcard character (*). The string must contain at least two characters. All the hosts that share the suffix are trusted.

-- A string that ends with the wildcard character (*). The string must contain at least two characters. All the hosts that share the prefix are trusted.

-- All NetBIOS names are trusted (for example, strings that do not contain a period).

-- A string without the wildcard character (*): The host named by the string is trusted.

Note: When the TrustedHosts value is set with the Set-Item cmdlet, the Set-Item cmdlet supports an additional parameter -Concatenate. The following example will append a new value (*.domain2.com) to the old value stored in TrustedHost:

Set-Item .\TrustedHosts *.domain2.com -Concatenate -Force

Cmdlets supported:

  • Clear-Item

  • Get-Item

  • Set-Item

URI <String>

Identifies the URI for which access is authorized based on the value of the Sddl parameter.

Cmdlets supported:

  • Get-Item

URLPrefix <String>

A URL prefix on which to accept HTTP or HTTPS requests. This is a string containing only the characters a-z, A-Z, 9-0, underscore (_) and backslash (/). The string must not start with or end with a backslash (/). For example, if the computer name is SampleComputer, the WS-Management client would specify http://SampleMachine/URLPrefix in the destination address.

Cmdlets supported:

  • Clear-Item

  • Get-Item

  • Set-Item

UserName <String>

Specifies the user name for a local account or for a domain account. It cannot have a value of NULL.

The client can specify the credentials to use when creating a shell on a computer. The user name must be specified in the domain\user_name format for a domain account. The user name must be specified in the server_name\user_name format for a local account on a server computer.

If this structure is used, it must have both the username and password fields specified . It can be used with Basic, Digest, Negotiate, or Kerberos authentication. The client must explicitly specify the credentials when either Basic or Digest authentication is used.

Cmdlets supported:

  • Get-Item

  • Set-Item

Value <String>

Specifies the value of an initialization parameter, which is a plug-in-specific value that is used to specify configuration options.

Cmdlets supported:

  • Get-Item

  • Set-Item

XMLRenderingType <String>

Specifies the format in which XML is passed to plug-ins through the WSMAN_DATA object. The following are valid values:

Text: Incoming XML data is contained in a WSMAN_DATA_TYPE_TEXT structure, which represents the XML as a PCWSTR memory buffer.

XMLReader: Incoming XML data is contained in a WSMAN_DATA_TYPE_WS_XML_READER structure, which represents the XML as an XmlReader object, which is defined in the WebServices.h header file.

Cmdlets supported:

  • Get-Item

  • Set-Item

xmlns <String>

A string that specifies specifies a Uniform Resource Name (URN) that uniquely identifies the namespace.

Cmdlets supported:

  • Get-Item

  • Set-Item

lang <String>

A string that specifies a language, or a language-region with language and region separated by a hyphen.

Cmdlets supported:

  • Get-Item

  • Set-Item

HTTP <Unsigned Short Integer>

Specifies the port that the client will use when HTTP is used. By default, HTTP uses port 80. You can specify any value from 1 through 65535.

Cmdlets supported:

  • Get-Item

  • Set-Item

HTTPS <Unsigned Short Integer>

Specifies the port that the client will use when HTTPS is used. By default, HTTPS uses port 443. You can specify any value from 1 through 65535.

Cmdlets supported:

  • Get-Item

  • Set-Item

MaxShellRunTime <Unsigned Long Integer>

Note: This value is deprecated and the value is no longer used.

Cmdlets supported:

  • Get-Item

MaxShellRunTime <Unsigned Long Integer>

Note: This value is deprecated and the value is no longer used.

Cmdlets supported:

  • Get-Item


Windows PowerShell Integrated Scripting Environment (ISE) Help

The Windows PowerShell Integrated Scripting Environment (ISE) is a host application that enables you to write, run, and test scripts and modules in a friendly environment. Key features such as syntax-coloring, tab completion, visual debugging, Unicode-compliance, and context-sensitive Help provide a rich scripting experience.

Features in the Windows PowerShell ISE include:

  • A Command Pane for running interactive commands, just as you would in the Windows PowerShell console. Just type a command and press Enter.

  • An Output Pane that captures the output of the commands.

  • A Script Pane to create, edit, debug, and run, functions, scripts and modules.

  • Multiple PowerShell tabs, each with its own Command Pane and Script Pane to allow you to simultaneously work on several independent tasks.

  • The ability to edit text in complex scripts and right-to-left languages.

Note:

Because Windows PowerShell ISE requires a user interface, it is not available on core installations of Windows Server. It is an optional component on server installations. Window PowerShell ISE is built on the Windows Presentation Foundation (WPF). If the graphical elements of Windows PowerShell ISE do not render correctly on your system, you might resolve the problem by adding or adjusting the graphics rendering settings on your system. This might be required if the computer has an older video driver or you are using virtualization software. For more information, see "Graphics Rendering Registry Settings" in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=144711.

The following sections provide information that will help you to get started with the Windows PowerShell ISE.

  • Exploring Windows PowerShell ISE

  • Using Windows PowerShell ISE

  • Accessibility in Windows PowerShell ISE

The following section describes the Windows PowerShell ISE object model and shows how you can use it in scripting.

  • The Windows PowerShell ISE Scripting Object Model

See Also

  • Windows PowerShell Getting Started Guide
  • Windows PowerShell Help


Exploring Windows PowerShell ISE

You can use the Windows PowerShell Integrated Scripting Environment (ISE) to create, run, and debug commands and scripts. The Windows PowerShell ISE consists of the menu bar, Windows PowerShell tabs, the toolbar, script tabs, a Script Pane, an Output Pane, a Command Pane, a status bar, a text-size slider and context-sensitive Help.

Menu Bar

The menu bar contains the File, Edit, View, Debug, and Help menus. Buttons on the menus allow you to perform tasks related to writing and running scripts and running commands in the Windows PowerShell ISE. Additionally, an Add-ons menu may be placed on the menu bar by running certain scripts that use the Windows PowerShell ISE Scripting Object Model.

Windows PowerShell Tabs

A Windows PowerShell tab is the environment in which Windows PowerShell runs. You can open new Windows PowerShell tabs in the Windows PowerShell ISE to create separate environments on your local computer or on remote computers. You may have a maximum of eight PowerShell tabs simultaneously open.

Toolbar

The following buttons are located on the toolbar.

Button | Function
New | Opens a new script.
Open | Opens an existing script or file.
Save | Saves a script or file.
Cut | Cuts the selected text and copies it to the clipboard.
Copy | Copies the selected text to the clipboard.
Paste | Pastes the contents of the clipboard at the cursor location.
Clear Output Pane | Clears all content in the Output Pane.
Undo | Reverses the action that was just performed.
Redo | Performs the action that was just undone.
Run Script | Runs a script.
Run Selction | Runs a selected portion of a script.
Stop Execution | Stops a script that is running.
New Remote PowerShell Tab | Creates a new PowerShell Tab that establishes a session on a remote computer. A dialog box appears and prompts you to enter details required to establish the remote connection.
Start PowerShell.exe | Opens a PowerShell Console.
Show Script Pane Top | Moves the Script Pane to the top in the display.
Show Script Pane Right | Moves the Script Pane to the right in the display.
Show Script Pane Maximized | Maximizes the Script Pane.

Script Tab

Displays the name of the script you are editing. You can click a script tab to select the script you want to edit.

When you point to the script tab, the fully qualified path to the script file appears in a tooltip.

Script Pane

Allows you to create and run scripts. You can open, edit and run existing scripts in the Script Pane.

Output Pane

Displays the results of the commands and scripts you have run. You can also copy and clear the contents in the Output Pane.

Command Pane

Allows you to write commands. You can run a one line command or a multiline command in the Command Pane. Press SHIFT+ENTER to enter each line of a multiline command, and press ENTER after the last line to execute the multiline command. The prompt displayed on top of the Command Pane shows the path to the current working directory.

Status Bar

Allows you to see whether the commands and scripts that you run are complete. The status bar is at the very bottom of the display. Selected portions of error messages are displayed on the status bar.

Text-Size Slider

Increases or decreases the size of the text on the screen.

Context-Sensitive Help

Offers documentation for Windows PowerShell ISE as a compiled HTML Help file (.chm) with search functionality. You can open the Help by clicking Windows PowerShell Help on the Help menu. Depending on where the cursor is in any one of the panes when you click Help, if there is a cmdlet topic that matches the text around the cursor, Help opens the specific topic. If there is no match with the context, Help opens on the default page.

To exit Windows PowerShell ISE, click Close on the toolbar, or on the File menu, click Exit.

See Also

  • Windows PowerShell Integrated Scripting Environment (ISE) Help
  • Using Windows PowerShell ISE


Using Windows PowerShell ISE

In this section

How to Use Tab Completion in the Script Pane and the Command Pane
Provides the steps to perform tab completion in the Script Pane and the Command Pane.

How to Create a PowerShell Tab in Windows PowerShell ISE
Provides the steps to create a Windows PowerShell tab in Windows PowerShell ISE.

How to Use the Command Pane
Provides the steps for writing and running commands in the Command Pane.

How to Manage Results in the Output Pane
Provides the steps to manage results in the Output Pane.

How to Write and Run Scripts in the Script Pane
Provides the steps for writing and running scripts in the Script Pane.

How to Debug Scripts in Windows PowerShell ISE
Provides steps for debugging scripts in Windows PowerShell ISE

How to Use Profiles in Windows PowerShell ISE
Provides information about and steps for using profiles in Windows PowerShell ISE.

See Also

  • Exploring Windows PowerShell ISE
  • Windows PowerShell ISE Object Model Reference
  • Accessibility in Windows PowerShell ISE


How to Use Tab Completion in the Script Pane and the Command Pane

Tab completion provides automatic Help when you are typing in the Script Pane or in the Command Pane. Use the following steps to take advantage of this feature:

To automatically complete a command entry

In the Command Pane or Script Pane, type a few characters of a command and then press TAB to select the desired completion text. Tab completion helps with typing a cmdlet name, parameter name, variable name, object property name, or a path.

Note:

In the Script Pane, pressing TAB will automatically complete a command only when you are editing .ps1, .psd1, or .psm1 files. Tab completion works when you are typing in the Command Pane.

To automatically complete a cmdlet parameter entry

In the Command Pane or Script pane, type a cmdlet followed by a dash, and then press TAB.

For example, type get-process - and then press TAB to select from the parameters for the cmdlet.

See Also

  • Using Windows PowerShell ISE
  • How to Enter and Run a Command in the Command Pane


How to Create a PowerShell Tab in Windows PowerShell ISE

PowerShell tabs allow you to simultaneously create and use several execution environments within the same application. Each PowerShell tab corresponds to an execution environment.

Note:

Variables, functions, and aliases that you create in one PowerShell tab do not carry over from one PowerShell tab to another.

Use the following steps to open and close a PowerShell tab. To rename a PowerShell tab, set the DisplayName property on the PowerShell Tab scripting object.

To create and use a new PowerShell tab

  1. On the File menu, click New PowerShell Tab. The new PowerShell tab always opens as the active window. The PowerShell tabs are incrementally numbered in the order that they are opened. You can open a maximum of eight PowerShell tabs in an instance of ISE. When you have opened eight PowerShell tabs, the New PowerShell Tab button on the File menu appears dimmed and is unavailable until at least one PowerShell tab is closed.

  2. To make a PowerShell tab active, click the tab. To select from all PowerShell tabs that are open, on the View menu, click the PowerShell tab you want to use.

To create and use a new remote PowerShell tab

  • On the File menu, click New Remote PowerShell Tab to establish a session on a remote computer. A dialog box appears and prompts you to enter details required to establish the remote connection. The remote tab functions just like a local PowerShell tab, but the commands and scripts are run on the remote computer.

To close a PowerShell Tab

  1. Click the PowerShell tab that you want to close.

  2. On the File menu, click Close PowerShell Tab, or click the Close button in an active Powershell tab to close the tab.

  3. If you have unsaved files open in the PowerShell tab that you are closing, you will be prompted to save or discard them.

    For more information about how to save a script, see How to Save a Script.

See Also

  • Using Windows PowerShell ISE


How to Use the Command Pane

Use the topics below to write and run commands in the Command Pane.

In this section

How to Enter and Run a Command in the Command Pane
Provides the procedures for entering, running, and stopping a command in the Command Pane.

How to Edit Text in the Command Pane
Provides the steps for editing text in the Command Pane.

How to Add Required Parameters in the Parameter Prompt Dialog Box
Describes how to input required parameters for Windows PowerShell cmdlets.

See Also

  • Using Windows PowerShell ISE


How to Enter and Run a Command in the Command Pane

Use the following steps to enter, run, or stop a command in the Command Pane.

To enter a command

In the Command Pane, type a command. To enter multiple commands that you want to execute in sequence, type SHIFT+ENTER between commands. See How to Use Tab Completion in the Script Pane and the Command Pane for help in typing commands.

To run a command

After you have entered a command, in the Command Pane, press ENTER.

To stop a command

On the toolbar, click Stop Execution, or press CTRL+BREAK. CTRL+C can be used to stop a command, if the context is unambiguous. For example, if some text has been selected in the current Pane, then CTRL+C will map to a copy operation.

See Also

  • How to Use the Command Pane
  • How to Use Tab Completion in the Script Pane and the Command Pane


How to Edit Text in the Command Pane

Use the following steps to edit text in the Command Pane. You can copy, cut, and paste text. You can also undo and redo the last performed action. The keyboard shortcuts for performing these actions are the same as those used for all Windows applications.

To copy text in the Command Pane

  1. In the Command Pane, select the text that you want to copy.

  2. On the toolbar, click Copy, or on the Edit menu, click Copy.

To cut text in the Command Pane

  1. In the Command Pane, select the text that you want to cut.

  2. On the toolbar, click Cut, or on the Edit menu, click Cut.

To paste text into the Command Pane

On the Command toolbar, click Paste, or on the Edit menu, click Paste.

To add a line in the Command Pane

In the Command Pane, click to place the cursor where you want to add the new line, and then press SHIFT+ENTER.

To undo an action in the Command Pane

On the toolbar, click Undo, or on the Edit menu, click Undo.

To redo an action in the Command Pane

On the Command toolbar, click Redo, or on the Edit menu, click Redo.

See Also

  • How to Use the Command Pane
  • How to Use Tab Completion in the Script Pane and the Command Pane


How to Add Required Parameters in the Parameter Prompt Dialog Box

Parameters provide a way to select options or provide input to a Windows PowerShell cmdlet. Some parameters are required and others are optional. If you enter a cmdlet without specifying its required parameters, Windows PowerShell prompts you to enter each required parameter. In the Windows PowerShell console you are prompted at the command line. In Windows PowerShell ISE a Parameter Prompt dialog box appears that provides a parallel functionality to the Windows PowerShell console interactive behavior. The dialog box cycles through the required parameters in sequence.

Note:

An important point of difference between the Windows PowerShell console experience and the Windows PowerShell ISE experience is the way a required array parameter is entered. The Parameter Prompt dialog box provides an OK button that functions the same way as the ENTER key. After you enter a value for the array parameter, you are prompted for the next value when you click OK or when you press ENTER. Clicking OK or pressing ENTER without entering a value signals the end of the array, the same way that pressing the ENTER key without entering a value signals the end of the array on the Windows PowerShell console. Note that the Cancel button on the Parameter Prompt dialog box cancels the entire command and not the last entered value in the array. In that sense, the Cancel button is the counterpart for CTRL+C on the Windows PowerShell console.

Use of the Parameter Prompt Dialog Box

  1. In the Command Pane, type start-sleep and press ENTER. You will see the Parameter Prompt Dialog box appear. You will be prompted to give a value of the required parameter “Seconds”.

  2. Type a number in the text box, and click OK. The start-sleep command runs for the specified number of seconds.

  3. Experiment by clicking Cancel instead of OK to see that it cancels the command.

Use of the Parameter Prompt Dialog Box to Enter a Required Array Parameter

  1. In the Script Pane, open a new script file and type the following lines.

    $var1 = 1
$var2 = 2
$var3 = 3
clear-variable
    On the toolbar click Run Script . You will see the Parameter Prompt Dialog box appear, and you will be prompted to provide a value for the required parameter “Name” for the clear-variable cmdlet. However, Name is an array parameter, so you will be prompted with “Name[0]”.

  2. In the Parameter text box, type “var1” and click OK or press ENTER. You will be prompted for subsequent array values. When prompted with “Name[1]”, in the Parameter text box, type “var2” and press ENTER. Click OK without entering a third value to mark the end of the array.

  3. Next, in the Command Pane type the following lines to see the values of the three variables. The values of var1 and var2 have been cleared, but var3 still has its assigned value.

    $var1
$var2
$var3
  4. Experiment by clicking Cancel instead of OK in the Parameter Prompt dialog box to see that it cancels the command.

See Also

  • about_Parameters
  • about_Command_Syntax
  • How to Use the Command Pane


How to Manage Results in the Output Pane

The Output Pane displays the results of the cmdlets you type and the scripts that you run. It also displays error messages.

Use the following steps to manage results in the Output Pane.

To select some or all of the results in the Output Pane

  1. Move the cursor to the Output Pane by clicking anywhere in the Output Pane, or by clicking Go to Output Pane on the View menu.

  2. In the Output Pane, select the results you want to work with.

To copy and paste results from the Output Pane

  1. To copy the selected text, click Copy on the toolbar.

  2. To paste the selected text at a current cursor position, click Paste on the toolbar.

To clear the results in the Output Pane

You cannot cut selected text from the Output Pane. However, you can clear the results in the Output Pane. To clear results, do one of the following:

  • On the toolbar, click Clear Output Pane

  • In the Command Pane, type “clear-host” and then press ENTER.

  • In the Command Pane, type “cls” and then press ENTER.

See Also

  • Using Windows PowerShell ISE


How to Write and Run Scripts in the Script Pane

Use the topics below to create, edit, run, and save scripts in the Script Pane.

In this section

How to Create and Run a Script
How to Manage and Close Script Tabs
How to Edit Text in the Script Pane
How to Save a Script

See Also

  • Using Windows PowerShell ISE


How to Create and Run a Script

Use the following steps to create and run a script in the Script Pane.

You can open and edit a file type in the Script Pane. Specific file types of interest in Windows PowerShell are script files (.ps1), script data files (.psd1), and script module files (.psm1). These file types are syntax colored in the Script Pane editor. Other common file types you may open in the Script Pane are configuration files (.ps1xml), XML files, and text files.

Note:

The Windows PowerShell execution policy determines whether you can run scripts and load Windows PowerShell profiles and configuration files. The default execution policy, Restricted, prevents all scripts from running, and prevents loading profiles. To change the execution policy to allow profiles to load and be used, see about_Signing and Set-ExecutionPolicy

To create a new script file

On the toolbar, click New , or on the File menu, click New. The created file appears in a new tab. By default a file of type script (.ps1) is created, but it can be saved with a new name and extension. Multiple script files can be created in the same PowerShell tab.

To open an existing script

On the toolbar, click Open…, or on the File menu, click Open. In the Open dialog box, select the file you want to open. The opened file appears in a new tab.

To display the file path

On the file tab, point to the file name. The fully qualified path to the script file appears in a tooltip.

To run a script

On the toolbar, click Run Script, or on the File menu, click Run.

To run a portion of a script

  1. In the Script Pane, select a portion of a script.

  2. On the File menu, click Run Selection, or on the toolbar, click Run Selection.

To stop a running script

On the toolbar, click Stop Execution, press CTRL+BREAK, or on the File menu, click Stop Execution. Pressing CTRL+C also works unless some text has been selected, in which case it maps to the copy function for the selected text.

See Also

  • How to Write and Run Scripts in the Script Pane
  • Using Windows PowerShell ISE


How to Edit Text in the Script Pane

Use the following steps to edit text in the Script Pane. You can copy, cut, paste, find, and replace text. You can also undo and redo the last action you just performed. The keyboard shortcuts for performing these actions are the same as those used for all Windows applications.

To enter text in the Script Pane

  1. Move the cursor to the Script Pane by clicking anywhere in the Script Pane, or by clicking Go to Script Pane in the View menu.

  2. Create a script. Syntax coloring and tab completion make this a richer experience in Windows PowerShell ISE.

  3. See How to Use Tab Completion in the Script Pane and the Command Pane for details about using the tab completion feature to help in typing.

To find text in the Script Pane

  1. To find text anywhere, on the Edit menu, click Find in Script.

  2. To find text after the cursor, on the Edit menu, click Find Next in Script.

  3. To find text before the cursor, on the Edit menu, click Find Previous in Script.

To go to a particular line of text in the Script Pane

  1. In the Script Pane, on the Edit menu, click Go to Line.

  2. Enter a line number.

To copy text in the Script Pane

  1. In the Script Pane, select the text that you want to copy.

  2. On the toolbar, click Copy, or on the Edit menu, click Copy.

    Note:

    The shortcut CTRL+C can be used to copy selected text when a selection has been made. The shortcut CTRL+C can be used to stop the execution of a command when no text has been selected.

To cut text in the Script Pane

  1. In the Script Pane, select the text that you want to cut.

  2. On the toolbar, click Cut, or on the Edit menu, click Cut.

To paste text into the Script Pane

On the toolbar, click Paste, or on the Edit menu, click Paste.

To undo an action in the Script Pane

On the toolbar, click Undo, or on the Edit menu, click Undo.

To redo an action in the Script Pane

On the toolbar, click Redo, or on the Edit menu, click Redo.

To replace text in the Script Pane

On the Edit menu, click Replace in Script.

See Also

  • Windows PowerShell About Help Topics
  • Windows PowerShell Cmdlet Help Topics
  • How to Create and Run a Script
  • How to Save a Script
  • How to Manage and Close Script Tabs
  • How to Use Tab Completion in the Script Pane and the Command Pane


How to Save a Script

Use the following steps to save and name a script. An asterisk appears next to the script name to mark a file that has not been saved since it was altered. The asterisk disappears when the file is saved.

Note:

Windows PowerShell file types, namely, script files (.ps1), script data files (.psd1), and script module files (.psm1) are saved as Unicode. However, some file types such as command scripts (.cmd) must be saved in the ANSI (ASCII) format to run properly. If you create a command script using Windows PowerShell ISE, in order to save the file, use the SaveAs method on the $psISE.CurrentFile object.

To save a script

On the toolbar, click Save, or on the File menu, click Save.

To save and name a script

  1. On the File menu, click Save As. The Save As dialog box will appear.

  2. In the File name box, enter a name for the file.

  3. In the Save as type box, select a file type. For example, in the Save as type box, select “PowerShell Scripts (* .ps1)”.

  4. Click Save.

See Also

  • How to Create and Run a Script
  • How to Edit Text in the Script Pane
  • How to Manage and Close Script Tabs


How to Manage and Close Script Tabs

Use the following steps to manage files and to close them in the Script Pane.

To move from one script tab to another

To move from one script tab to another do one of the following:

  • Click the script tab you want to move to.

  • In the View menu, click the name of the script you want to move to.

To close a script tab

  1. Click the script tab of the script you want to close.

  2. Then, do one of the following:

    • Click Close on the script tab.

    • On the File menu, click Close.

    • If the file has been altered since it was last saved, you are prompted to save or discard it.

      For directions on how to save a script, see How to Save a Script .

See Also

  • How to Save a Script
  • How to Edit Text in the Script Pane
  • How to Save a Script


How to Debug Scripts in Windows PowerShell ISE

The topics in this section describe how to debug scripts on a local computer by using the Windows PowerShell ISE visual debugging features.

In this section

How to Set, Remove, Disable, Enable, and List Breakpoints
How to Start, Stop, and Continue Debugging
How to Step Over, Step Into, and Step Out While Debugging

See Also

  • Using Windows PowerShell ISE


How to Set, Remove, Disable, Enable, and List Breakpoints

You can set three types of breakpoints in the Windows PowerShell debugging environment: variable breakpoints, command breakpoints, and line breakpoints. Of these, in the Windows PowerShell ISE debugging environment, only line breakpoints highlighted and can be set by using the menu or the keyboard shortcuts. The other two types of breakpoints can still be set, but they are set from the command pane by using the Set-PSBreakpoint cmdlet. You can remove, enable, disable, and list all breakpoints. This section describes how you can perform debugging tasks in Windows PowerShell ISE by using the menus where available, and perform a wider range of commands from the Command Pane by using scripting.

Managing Breakpoints

Set a Breakpoint

Sets a line breakpoint in a Windows PowerShell script or function. A breakpoint can be set in a script only after it has been saved.

Right-click the line where you want to set a breakpoint, and then click Toggle Breakpoint. Or, click the line where you want to set a breakpoint, and on the Debug menu, click Toggle Breakpoint. The following script is an example of how you can set a variable breakpoint from the Command Pane by using the Set-PSBreakpoint cmdlet.

# This command sets a breakpoint on the Server variable in the Sample.ps1 script.
set-psbreakpoint -script sample.ps1 -variable Server

List All Breakpoints

Displays all breakpoints in the current session.

On the Debug menu, click List Breakpoints. The following script is an example of how you can list all breakpoints from the Command Pane by using the Get-PSBreakpoint cmdlet.

 # This command lists all breakpoints in the current session.
get-psbreakpoint

Remove a Breakpoint

Deletes a specific line breakpoint.

Right-click the line where you want to remove a breakpoint, and then click Toggle Breakpoint. Or, click the line where you want to remove a breakpoint, and on the Debug menu, click Toggle Breakpoint. The following script is an example of how to remove a breakpoint with a specified ID from the Command Pane by using the Remove-PSBreakpoint cmdlet.

# This command deletes the breakpoint with breakpoint ID 2.
remove-psbreakpoint -id 2

Remove All Breakpoints

Deletes all breakpoints from the current session.

On the Debug menu, click Remove All Breakpoints. The following script is an example of how to remove all breakpoints from the Command Pane by using the Remove-PSBreakpoint cmdlet.

# This command deletes all of the breakpoints in the current session.
get-breakpoint | remove-breakpoint

Disable a Breakpoint

Disables a specific line breakpoint.

Right-click the line where you want to disable a breakpoint, and then click Disable Breakpoint. Or, click the line where you want to disable a breakpoint, and on the Debug menu, click Disable Breakpoint. The following script is an example of how you can remove a breakpoint with a specified ID from the Command Pane by using the Disable-PSBreakpoint cmdlet.

# This command disables the breakpoint with breakpoint ID 0.
disable-psbreakpoint -id 0

Disable All Breakpoints

Disables all breakpoints in the current session.

On the Debug menu, click Disable all Breakpoints. The following script is an example of how you can disable all breakpoints from the Command Pane by using the Disable-PSBreakpoint cmdlet.

# This command disables all breakpoints in the current console.
# You can abbreviate this command as: "gbp | dbp".

get-psbreakpoint | disable-psbreakpoint

Enable a Breakpoint

Enables a specific line breakpoint.

Right-click the line where you want to enable a breakpoint, and then click Enable Breakpoint. Or, click the line where you want to enable a breakpoint, and then press F8 or, on the Debug menu, click Enable Breakpoint. The following script is an example of how you can enable specific breakpoints from the Command Pane by using the Enable-PSBreakpoint cmdlet.

# This command enables breakpoints with breakpoint IDs 0, 1, and 5.
enable-psbreakpoint -id 0, 1, 5

Enable All Breakpoints

Enables all breakpoints in the current session.

On the Debug menu, click Enable all Breakpoints. is the following script is an example of how you can enable all breakpoints from the Command Pane by using the Enable-PSBreakpoint cmdlet.

# This command enables all breakpoints in the current session.
# You can abbreviate the command as "gbp | ebp".

get-psbreakpoint | enable-psbreakpoint

See Also

  • about_Debuggers
  • Set-PSBreakpoint
  • Get-PSBreakpoint
  • Disable-PSBreakpoint
  • Enable-PSBreakpoint
  • Remove-PSBreakpoint
  • Get-PSCallStack


How to Start, Stop, and Continue Debugging

Before you start debugging, you must set one or more breakpoint. You cannot set a breakpoint unless the script that you want to debug is saved. For directions on of how to set a breakpoint, see How to Set, Remove, Disable, Enable, and List Breakpoints or Set-PSBreakpoint. After you start debugging, you cannot edit a script until you stop debugging. A script that has one or more breakpoints set is automatically saved before it is run.

To start debugging

On the Script title bar, click Run Script. The following changes occur when debugging starts:

  • The command prompt changes to “>>>” and is prefixed with “[DBG]” to indicate that debugging is in progress.

  • The first breakpoint is highlighted.

To continue debugging

  1. On the Debug menu, click Run/Continue or, in the Command Pane, type C and then press ENTER.

  2. Clicking Run/Continue causes the script to continue execution to the next breakpoint or to the end of the script.

To view the call stack

  1. On the Debug menu, click Display Call Stack or, in the Command Pane, type K and then press ENTER.

  2. The Output Pane displays the current call stack.

To stop debugging

On the Debug menu, click Stop Debugger, or, in the Command Pane, type Q and then press ENTER.

See Also

  • How to Set, Remove, Disable, Enable, and List Breakpoints
  • Set-PSBreakpoint
  • about_Debuggers
  • Set-StrictMode
  • How to Save a Script
  • How to Debug Scripts in Windows PowerShell ISE


How to Step Over, Step Into, and Step Out While Debugging

Use the following information to debug a script by stepping through it.

Stepping is the process of running one statement at a time. You can stop on a line of code, and examine the values of variables and the state of the system. The following table describes common debugging tasks such as stepping over, stepping into, and stepping out.

Debugging Task | Description | How to accomplish it in PowerShell ISE
Step Into | Executes the current statement and then stops at the next statement. If the current statement is a function or script call, then the debugger steps into that function or script, otherwise it stops at the next statement. | In the Command Pane, type S and press ENTER, or, on the Debug menu, click Step Into.
Step Over | Executes the current statement and then stops at the next statement. If the current statement is a function or script call then the debugger executes the whole function or script, and it stops at the next statement after the function call. | In the Command Pane, type V and press ENTER, or, on the Debug menu, click Step Over.
Step Out | Steps out of the current function and up one level if the function is nested. If in the main body, the script is executed to the end, or to the next breakpoint. The skipped statements are executed, but not stepped through. | In the Command Pane, type O and press ENTER, or, on the Debug menu, click Step Out.
Continue | Continues execution to the end, or to the next breakpoint. The skipped functions and invocations are executed, but not stepped through. | In the Command Pane, type C and press ENTER, or, on the Debug menu, click Run/Continue.

Debugging a script

  1. Set the breakpoints in the code you want to examine. For information about how to set breakpoints, see How to Set, Remove, Disable Enable, Disable, and List Breakpoints or Set-PSBreakpoint.

  2. On the Debug menu, click Run/Continue, or on the toolbar, click Run Script. Here is what you can expect:

    • Debugging starts. The script runs until it locates the first breakpoint and then stops. The breakpoint is highlighted.

    • The command prompt changes, and the prefix [DBG] appears on the Command Pane bar.

    • A message about the breakpoint that was encountered appears in the Output Pane. For example, “Hit Line breakpoint on 'C:\Users\name\Desktop\test.script.ps1:13”.

    The message contains the script name and details about the line breakpoint, variable breakpoint, or command breakpoint.

  3. From here you may step over, step into, step out, or continue. Continue causes the debugger to execute to the end of the script or to the next breakpoint.

  4. To find the value of a variable while you are debugging, hover over the variable in the Script Pane, or type the variable name in the Command Pane, and press ENTER. The Output Pane displays the value of the variable. Continue to step through the script, or perform other debugging tasks.

See Also

  • about_Debuggers
  • How to Debug Scripts in Windows PowerShell ISE


How to Use Profiles in Windows PowerShell ISE

Use the following topics to learn how to use profiles in the Windows PowerShell Integrated Scripting Environment (ISE).

Note:

Before performing the tasks in this section, see about_Profiles, or in the Command Pane, type, “get-help about_profiles” and press ENTER.

You can create one or more Windows PowerShell profiles for Windows PowerShell ISE and use them to add the variables, aliases, commands and functions that you use frequently. A profile affects every Windows PowerShell ISE session that you start. You can also use a profile to preserve the items that you customize in the Windows PowerShell ISE environment, such as color and font preferences.

Note:

The Windows PowerShell execution policy determines whether you can run scripts and load a profile or a configuration files. The default execution policy, “Restricted,” prevents all scripts from running, including profiles. If you use the “Restricted” policy, the profile does not load. For more information about execution policy, see about_Execution_Policies.

Selecting a Profile to Use in Windows PowerShell ISE

Windows PowerShell ISE supports profiles for the current user and all users of Windows PowerShell ISE. It also supports the Windows PowerShell profiles that apply to all hosts.

The profile that you use is determined by how you use Windows PowerShell and Windows PowerShell ISE.

  • If you use only Windows PowerShell ISE to run Windows PowerShell, then save all your items in one of the ISE-specific profiles, such as the CurrentUserCurrentHost profile for Windows PowerShell ISE or the AllUsersCurrentHost profile for Windows PowerShell ISE.

  • If you use multiple host programs to run Windows PowerShell, save your functions, aliases, variables, and commands in a profile that affects all host programs, such as the CurrentUserAllHosts or the AllUsersAllHosts profile, and save ISE-specific features, like color and font customization in the CurrentUserCurrentHost profile for Windows PowerShell ISE profile or the AllUsersCurrentHost profile for Windows PowerShell ISE.

The following are profiles that can be created and used in Windows PowerShell ISE. Each profile is saved to its own specific path.

Profile Type | Profile Path
“Current user, PowerShell ISE” | $profile.CurrentUserCurrentHost, or $profile
“All users, PowerShell ISE” | $profile.AllUsersCurrentHost
“Current user, All hosts” | $profile.CurrentUserAllHosts
“All users, All hosts” | $profile.AllUsersAllHosts

In this section

How to Create Profiles in Windows PowerShell ISE
Provides the procedures to create, move, and save profiles in the Windows PowerShell ISE.

See Also

  • about_Profiles
  • Using Windows PowerShell ISE


How to Create Profiles in Windows PowerShell ISE

Before you create a profile, you must know what type of profile you want to create. For more information, see about_Profiles, or in the Command Pane, type, “get-help about_profiles” and press ENTER.

To create a new profile

  1. To create a new “Current user, Windows PowerShell ISE” profile, type:

    if (!(test-path $profile ))
{new-item -type file -path $profile -force}
  2. To create a new “All users, Windows PowerShell ISE” profile, type:

    if (!(test-path $profile.AllUsersCurrentHost))
{new-item -type file -path $profile.AllUsersCurrentHost -force}
  3. To create a new “Current user, All Hosts” profile, type:

    if (!(test-path $profile.CurrentUserAllHosts))
{new-item -type file -path $profile.CurrentUserAllHosts -force}
  4. To create a new “All users, All Hosts” profile, type:

    if (!(test-path $profile.AllUsersAllHosts))
{new-item -type file -path $profile.AllUsersAllHosts-force}

To edit a profile

  1. Open the profile. For example, to open the Current user, Windows PowerShell ISE profile, type: psEdit $profile

  2. Add some items to your profile. The following are a few examples to get you started:

    • To change the default background color of the Output Pane to blue, in the profile file type: $psISE.Options.OutputPaneBackground = 'blue' . For more information about the $psISE variable, see The Windows PowerShell ISE Scripting Object Model.

    • To change font size to 20, in the profile file type: $psISE.Options.FontSize =20

  3. Save your profile file. On the File menu, click Save. Next time you open the Windows PowerShell ISE, your customizations will be applied.

See Also

  • about_Profiles
  • about_Signing
  • Set-ExecutionPolicy
  • How to Use Profiles in Windows PowerShell ISE
  • The Windows PowerShell ISE Scripting Object Model


Accessibility in Windows PowerShell ISE

The Accessibility Information topic in the Windows PowerShell ISE section contains accessibility information that you might find helpful as you work with Windows PowerShell Integrated Scripting Environment (ISE).

In this section

Accessibility Information

How to Change the Size and Location of the Command Pane and Script Pane

Keyboard Shortcuts

See Also

  • Windows PowerShell Integrated Scripting Environment (ISE) Help


Accessibility Information

Microsoft is committed to making its products and services easier for everyone to use. The following topics provide information about the features, products, and services that make Windows PowerShell ISE more accessible for people with disabilities.

  • Accessibility Features of Windows PowerShell ISE

  • Accessibility Features of Windows PowerShell ISE Help

Accessibility Features of Windows PowerShell ISE

Windows PowerShell ISE supports high contrast mode. For the visually impaired, breakpoint information is available through the cmdlets for managing breakpoints, such as Get-PSBreakpoint and Set-PSBreakpoint. For more information please see How to Set, Remove, Disable, Enable, and List Breakpoints. In addition to accessibility features and utilities in Microsoft Windows, the following features make Windows PowerShell ISE more accessible for people with disabilities:

  • Keyboard Shortcuts

  • Syntax Coloring Table and the ability to modify several other color settings using the $psISE.Options scripting object.

  • Text Size Change

Note:

The information in this section applies only to users who license Microsoft products in the United States. If you obtained this product outside of the United States, you can use the subsidiary information card that came with your software package or visit the Microsoft Accessibility Web site for a list of telephone numbers and addresses for Microsoft support services. You can contact your subsidiary to find out whether the type of products and services described in this section are available in your area. Information about accessibility is available in other languages, including Japanese and French.

Accessibility Features of Windows PowerShell ISE Help

Windows PowerShell ISE Help includes features that make it accessible to a wider range of users, including those who have limited dexterity, low vision, or other disabilities.

Keyboard shortcuts for using the Help window:

By using the following keyboard shortcuts in Help, you can quickly accomplish many common tasks.

To do this | Use this keyboard shortcut
Display the Help window. | F1
Switch the cursor between the Help topic pane and the navigation pane (tabs such as Contents, Search, and Index). | F6
Change between tabs (for example, Contents, Search, and Index) while in the navigation pane. | ALT + Underlined letter of the tab
Select the next hidden text or hyperlink. | TAB
Select the previous hidden text or hyperlink. | SHIFT+TAB
Perform the action for the selected Show All, Hide All, hidden text, or hyperlink. | ENTER
Display the Options menu to access any Help toolbar command. | ALT+O
Hide or show the pane containing the Contents, Search, and Index tabs. | ALT+O, and then press T
Display the previously viewed topic. | ALT+O, and then press B
Display the next topic in a previously displayed sequence of topics. | ALT+O, and then press F
Return to the specified home page. | ALT+O, and then press H
Stop the Help window from opening a Help topic (useful if you want to stop a Web page from downloading). | ALT+O, and then press S
Open the Internet Options dialog box for Microsoft Internet Explorer, where you can change accessibility settings. | ALT+O, and then press I
Refresh the topic (useful if you have linked to a Web page). | ALT+O, and then press R
Print all topics in a book or a selected topic only. | ALT+O, and then press P
Close the Help window. | ALT+F4
To change the appearance of a help topic

  1. To customize the colors, font styles, and font sizes used in Help, open the Help window.

  2. Click Options, and then click Internet Options.

  3. On the General tab, click Accessibility. Select Ignore colors specified on Web pages, Ignore font styles specified on Web pages, and Ignore font sizes specified on Web pages. You also can choose to use the settings specified in your own style sheet.

  4. To change the colors used in Help, see To change the color of the background or text in Help. To change the font, see To change the font in Help.

To change the color of the background or text in Help

  1. Open the Help window.

  2. Click Options, and then click Internet Options.

  3. On the General tab, click Accessibility. Then select Ignore colors specified on Web pages. You also can choose to use the settings specified in your own style sheet.

  4. To customize the colors used in Help, on the General tab, click Colors. Clear the Use Windows Colors check box, and then select the font and background colors that you want to use.

    Note:

    If you change the background color of the Help topics in the Help window, the change also affects the background color when you view a Web page in a browser.
To change the font in Help

  1. Open the Help window.

  2. Click Options, and then click Internet Options.

  3. On the General tab, click Accessibility. To use the same settings as those used in your instance of Microsoft Internet Explorer, select Ignore font styles specified on Web pages and Ignore font sizes specified on Web pages. You also can choose to use the settings specified in your own style sheet.

  4. To customize the font style used in Help, on the General tab, click Fonts, and then click the font style you want.

    Note:

    If you change the font of the Help topics in the Help window, the change also affects the font when you view a Web page in a browser.

To increase or decrease the size of the text in Windows PowerShell ISE

  • You can change the size of the text that appears in the Command, Script, and Output Panes by using the text-size slider in the bottom right-hand corner in ISE. Alternately, you can increase the FontSize by using the Options scripting object. To increase the font size, move the text-size slider to right, or in the View menu, click Zoom In. To decrease the font size, move the text-size slider to left, or in the View menu, click Zoom Out.

See Also

  • Keyboard Shortcuts
  • How to Change the Size and Location of the Command Pane and Script Pane


How to Change the Size and Location of the Command Pane and Script Pane

You can use the following steps to change the size and location of the Command Pane and the Script Pane. When you open the Windows PowerShell Integrated Scripting Environment (ISE) again, the size and location changes you made will be retained.

To resize the Command Pane

  1. Pause the pointer on the split line between the Command Pane and Output Pane.

  2. When the mouse pointer changes to a two-headed arrow, drag the border to change the size of the pane.

To move the Command Pane

  1. To move the Command Pane above the Output Pane, on the Command Pane bar, click Move Command Pane Up, or in the View menu, click Command Pane Up.

  2. To move the Command Pane below the Output Pane, on the Command Pane bar, click Move Command Pane Down, or in the View menu, clear Command Pane Up.

  3. By default, the Command Pane is located below the Output Pane.

To resize the Script Pane

  1. Pause the pointer on the split line between the Script Pane and the other panes.

  2. When the mouse pointer changes to a two-headed arrow, drag it to change the size of the pane.

To move the Script Pane

Do one of the following

  • To move the Script Pane to the right of the Command and Output Panes, in the toolbar, click Show Script Pane Right, or in the View menu, click Show Script Pane Right.

  • To move the Script Pane above the Command and Output Panes, in the toolbar, click Show Script Pane Up, or in the View menu, click Show Script Pane Up.

To hide the Script Pane

To hide the Script Pane, on the Script Pane bar, click Hide Script Pane, or in the View menu, clear Show Script Pane.

To display the Script Pane

To display the Script Pane, on the Script Pane bar, click Show Script Pane, or in the View menu, click Show Script Pane.

To maximize the Script Pane

To maximize the Script Pane, on the Script Pane bar, click Show Script Pane Maximized, or in the View menu, click Show Script Pane Maximized.

See Also

  • Accessibility in Windows PowerShell ISE


Keyboard Shortcuts

Use the following keyboard shortcuts to perform actions in the Windows PowerShell Integrated Scripting Environment (ISE).

Keyboard shortcuts for editing text

You can use the following keyboard shortcuts when you edit text.

Action | Keyboard Shortcuts | Use in
Copy | CTRL+C | Script Pane, Command Pane, Output Pane
Cut | CTRL+X | Script Pane, Command Pane
Find in Script | CTRL+F | Script Pane
Find Next in Script | F3 | Script Pane
Find Previous in Script | SHIFT+F3 | Script Pane
Paste | CTRL+V | Script Pane, Command Pane
Redo | CTRL+Y | Script Pane, Command Pane
Replace in Script | CTRL+H | Script Pane
Save | CTRL+S | Script Pane
Select All | CTRL+A | Script Pane, Command Pane, Output Pane
Undo | CTRL+Z | Script Pane, Command Pane

Keyboard shortcuts for running scripts

You can use the following keyboard shortcuts when you run scripts in the Script Pane.

Action Keyboard Shortcut

New

CTRL+N

Open

CTRL+O

Run

F5

Run Selection

F8

Stop Execution

CTRL+BREAK. CTRL+C can be used when the context is unambiguous (when there is no text selected).

Tab (to next script)

CTRL+TAB

Note:

Tab to next script works only when you have a single PowerShell tab open, or when you have more than one PowerShell tab open, but the focus is in the Script Pane.

Tab (to previous script)

CTRL+SHIFT+TAB

Note:

Tab to previous script works when you have only one PowerShell tab open, or if you have more than one PowerShell tab open, and the focus is in the Script Pane.

Keyboard shortcuts for customizing the view

You can use the following keyboard shortcuts to customize the view in Windows PowerShell ISE. They are accessible from all the panes in the application.

Action | Keyboard Shortcut
Go to Command Pane | CTRL+D
Go to Output Pane | CTRL+SHIFT+O
Go to Script Pane | CTRL+I
Show Script Pane | CTRL+R
Hide Script Pane | CTRL+R
Move Script Pane Up | CTRL+1
Move Script Pane Right | CTRL+2
Maximize Script Pane | CTRL+3
Zoom In | CTRL+PLUS SIGN
Zoom Out | CTRL+MINUS SIGN

Keyboard shortcuts for debugging scripts

You can use the following keyboard shortcuts when you debug scripts.

Action | Keyboard Shortcut | Use in
Run/Continue | F5 | Script Pane, when debugging a script
Step Into | F11 | Script Pane, when debugging a script
Step Over | F10 | Script Pane, when debugging a script
Step Out | SHIFT+F11 | Script Pane, when debugging a script
Display Call Stack | CTRL+SHIFT+D | Script Pane, when debugging a script
List Breakpoints | CTRL+SHIFT+L | Script Pane, when debugging a script
Toggle Breakpoint | F9 | Script Pane, when debugging a script
Remove All Breakpoints | CTRL+SHIFT+F9 | Script Pane, when debugging a script
Stop Debugger | SHIFT+F5 | Script Pane, when debugging a script
Note:

You can also use the keyboard shortcuts designed for the Windows PowerShell console when you debug scripts in Windows PowerShell ISE. To use these shortcuts, you must type the shortcut in the Command Pane and press ENTER.

Action | Keyboard Shortcut | Use in
Continue | C | Command Pane, when debugging a script
Step Into | S | Command Pane, when debugging a script
Step Over | V | Command Pane, when debugging a script
Step Out | O | Command Pane, when debugging a script
Repeat Last Command (for Step Into or Step Over) | ENTER | Command Pane, when debugging a script
Display Call Stack | K | Command Pane, when debugging a script
Stop Debugging | Q | Command Pane, when debugging a script
List the Script | L | Command Pane, when debugging a script
Display Console Debugging Commands | H or ? | Command Pane, when debugging a script

Keyboard shortcuts for Windows PowerShell tabs

You can use the following keyboard shortcuts when you use Windows PowerShell tabs.

Action | Keyboard Shortcut
Close PowerShell Tab | CTRL+W
New PowerShell Tab | CTRL+T
Previous PowerShell tab | CTRL+SHIFT+TAB. This shortcut works only when no files are open on any PowerShell tab.
Next Windows PowerShell tab | CTRL+TAB. This shortcut works only when no files are open on any PowerShell tab.

Keyboard shortcuts for starting and exiting

You can use the following keyboard shortcuts to start the Windows PowerShell console (PowerShell.exe) or to exit Windows PowerShell ISE.

Action | Keyboard Shortcut
Exit | ALT+F4
Start PowerShell.exe (Windows PowerShell console) | CTRL+SHIFT+P


The Windows PowerShell ISE Scripting Object Model

Windows PowerShell Integrated Scripting Environment (ISE) exposes its underlying scripting object model to allow users to write Windows PowerShell scripts that manipulate the various visual and functional aspects of Windows PowerShell ISE. Scripting objects, their properties, and their methods are defined specifically for this purpose.

In This Section

Purpose of the Windows PowerShell ISE Scripting Object Model
The ISE object hierarchy
Other Useful Scripting Objects
Windows PowerShell ISE Object Model Reference

See Also

  • Windows PowerShell Integrated Scripting Environment (ISE) Help


Purpose of the Windows PowerShell ISE Scripting Object Model

Objects are associated with the form and function of Windows PowerShell Integrated Scripting Environment (ISE). The object model reference provides details about the member properties and methods that these objects expose. Examples are provided to show how you can use scripts to directly access these methods and properties. The scripting object model makes the following range of tasks easier.

Customizing the appearance of the ISE

You can use the object model to modify the application settings and options. For example, you can modify them as follows:

  • You can change the color of errors, warnings, verbose outputs, and debug outputs.

  • You can get or set the background colors for the Command pane, the Output pane, and the Script pane.

  • You can set the foreground color for the Output pane.

  • You can set the font name and font size for Windows PowerShell ISE.

  • You can configure warnings. This includes warnings that are issued when a file is opened in multiple PowerShell tabs or when a script in the file is run before the file has been saved.

  • You can switch between a view where the Script Pane and the Output Pane are side-by-side and a view where the Script Pane is on top of the Output Pane. You can dock the Command Pane at the bottom or the top of the Output Pane.

Enhancing the functionality of the ISE

You can use the object model to enhance the functionality of Windows PowerShell ISE. For example, you can:

  • Make additions and modifications to the instance of the Windows PowerShell ISE itself. For example, you can change the menus by adding new menu items and by mapping the new menu items to scripts.

  • Create scripts that perform some of the tasks that you can perform by using the menu commands and buttons in Windows PowerShell ISE. For example, you can add, remove, or select a PowerShell tab.

  • Complement tasks that can be performed by using menu commands and buttons. For example, you can rename a PowerShell tab.

  • Manipulate text buffers for the Command pane, the Output pane, and the Script pane that are associated with a file. For example, you can:

    • Get or set all text.

    • Get or set a text selection.

    • Run a script or run a selected portion of a script.

    • Scroll a line into view.

    • Insert text at a caret position.

    • Select a block of text.

    • Get the last line number.

  • Perform file operations. For example, you can:

    • Open a file, save a file, or save a file with a different name.

    • Determine whether a file has been changed since it was last saved.

    • Get the file name.

    • Select a file.

Automating tasks

You can use the scripting object model to create keyboard shortcuts for frequent operations.

See Also

  • The ISE object hierarchy
  • Windows PowerShell ISE Object Model Reference
  • The Windows PowerShell ISE Scripting Object Model


The ISE object hierarchy

This topic shows the hierarchy of objects that are part of the Windows PowerShell Integrated Scripting Environment (ISE). Clicking an object takes you to the reference documentation for the class in the Microsoft.PowerShell.Host.ISE namespace that defines the object.

$psISE Object

The $psISE object is the root object of the Windows PowerShell Integrated Scripting Environment (ISE) object hierarchy. Located at the top level, it exposes the following four objects:

$psISE.CurrentFile

$psISE. CurrentPowerShellTab

$psISE.Options

$psISE.PowerShellTabs

$psISE.CurrentFile

The $psISE.CurrentFile object makes the following objects available for scripting:

  • $psISE.CurrentFile.DisplayName

  • $psISE.CurrentFile.Editor The $psISE.CurrentFile.Editor object in turn makes these objects available for scripting:

    • $psISE.CurrentFile.Editor.CaretColumn

    • $psISE.CurrentFile.Editor.CaretLine

    • $psISE.CurrentFile.Editor.LineCount

    • $psISE.CurrentFile.Editor.SelectedText

    • $psISE.CurrentFile.Editor.Text

  • $psISE.CurrentFile.Encoding

  • $psISE.CurrentFile.FullPath

  • $psISE.CurrentFile.IsSaved

  • $psISE.CurrentFile.IsUntitled

$psISE.CurrentPowerShellTab

The $psISE.CurrentPowerShellTab object makes the following objects available for scripting:

  • $psISE.CurrentPowerShellTab.AddOnsMenu The $psISE.CurrentPowerShellTab.AddOnsMenu object makes the following objects available for scripting:

    • $psISE.CurrentPowerShellTab.AddOnsMenu.Action

    • $psISE.CurrentPowerShellTab.AddOnsMenu.DisplayName

    • $psISE.CurrentPowerShellTab.AddOnsMenu.Shortcut

    • $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus

  • $psISE.CurrentPowerShellTab.CanInvoke

  • $psISE.CurrentPowerShellTab.CommandPane The $psISE.CurrentPowerShellTab.CommandPane object makes the following objects available for scripting:

    • $psISE.CurrentPowerShellTab.CommandPane.CaretColumn

    • $psISE.CurrentPowerShellTab.CommandPane.CaretLine

    • $psISE.CurrentPowerShellTab.CommandPane.LineCount

    • $psISE.CurrentPowerShellTab.CommandPane.SelectedText

    • $psISE.CurrentPowerShellTab.CommandPane.Text

  • $psISE.CurrentPowerShellTab.DisplayName

  • $psISE.CurrentPowerShellTab.ExpandedScript

  • $psISE.CurrentPowerShellTab.Files

  • $psISE.CurrentPowerShellTab.Output The $psISE.CurrentPowerShellTab.Output object makes the following objects available for scripting:

    • $psISE.CurrentPowerShellTab.Output.CaretColumn

    • $psISE.CurrentPowerShellTab.Output.CaretLine

    • $psISE.CurrentPowerShellTab.Output.LineCount

    • $psISE.CurrentPowerShellTab.Output.SelectedText

    • $psISE.CurrentPowerShellTab.Output.Text

  • $psISE.CurrentPowerShellTab.Prompt

  • $psISE.CurrentPowerShellTab.StatusText

$psISE.Options

The $psISE.Options object makes the following objects available for scripting:

  • $psISE.Options.CommandPaneBackgroundColor

  • $psISE.Options.CommandPaneUp

  • $psISE.Options.DebugBackgroundColor

  • $psISE.Options.DebugForegroundColor

  • $psISE.Options.DefaultOptions

  • $psISE.Options.ErrorBackgroundColor

  • $psISE.Options.ErrorForegroundColor

  • $psISE.Options.FontName

  • $psISE.Options.Fontsize

  • $psISE.Options.OutputPaneBackgroundColor

  • $psISE.Options.OutputPaneTextForegroundColor

  • $psISE.Options.OutputPaneTextBackgroundColor

  • $psISE.Options.ScriptPaneBackgroundColor

  • $psISE.Options.ScriptPaneForegroundColor

  • $psISE.Options.SelectedScriptPaneState

  • $psISE.Options.ShowToolBar

  • $psISE.Options.ShowWarningBeforeSavingOnRun

  • $psISE.Options.ShowWarningForDuplicateFiles

  • $psISE.Options.TokenColors

  • $psISE.Options.UseLocalHelp

  • $psISE.Options.VerboseBackgroundColor

  • $psISE.Options.VerboseForegroundColor

  • $psISE.Options.WarningBackgroundColor

  • $psISE.Options.WarningForegroundColor

See Also

  • Windows PowerShell ISE Object Model Reference
  • The Windows PowerShell ISE Scripting Object Model


Other Useful Scripting Objects

The following objects provide additional scripting functionality in Windows PowerShell ISE. They are not part of the $psISE hierarchy.

Useful Scripting objects

$psUnsupportedConsoleApplications

There are some limitations on how Windows PowerShell ISE interacts with console applications. A command or an automation script that requires user intervention may not work the way it works from the Windows PowerShell console. You may want to block these commands or scripts from running in the Windows PowerShell ISE Command pane. The $psUnsupportedConsoleApplications object keeps a list of such commands. If you try to run the commands in this list, you get a message saying that they are not supported. The following script adds an entry to the list:

# List the unsupported commands
psUnsupportedConsoleApplications
# Add a command to this list
psUnsupportedConsoleApplications.Add(“Mycommand”)
#Show the augmented list of commands
psUnsupportedConsoleApplications

$psLocalHelp

This is a dictionary object that maintains a context-sensitive mapping between Help topics and their associated links in the local compiled HTML Help file. It is used to locate the local Help for a particular topic. You can add or delete topics from this list. Below are some example key-value pairs contained in $psLocalHelp:

# See the local help map
$psLocalHelp |Format-List

Sample Output:

Key : Add-Computer | Value : WindowsPowerShellHelp.chm::/html/093f660c-b8d5-43cf-aa0c-54e5e54e76f9.htm
Key : Add-Content | Value : WindowsPowerShellHelp.chm::/html/0c836a1b-f389-4e9a-9325-0f415686d194.htm

The following script adds an entry to the list:

$psLocalHelp.Add("get-myNoun","c:\MyFolder\MyHelpChm.chm::/html/0198854a-1298-57ae-aa0c-87b5e5a84712.htm")

$psOnlineHelp

This is a dictionary object that maintains a context-sensitive mapping between topic titles of Help topics and their associated external URLs. It is used to locate the Web Help for a particular topic. You can add or delete topics from this list.

$psOnlineHelp |format-list

Sample Output:

Key : Add-Computer | Value : http://go.microsoft.com/fwlink/?LinkID=135194
Key : Add-Content | Value : http://go.microsoft.com/fwlink/?LinkID=113278

The following script adds an entry to the list:

$psOnlineHelp.Add("get-myNoun","http://www.mydomain.com/MyNoun.html")

See Also

  • The Windows PowerShell ISE Scripting Object Model


Windows PowerShell ISE Object Model Reference

Object Model Reference

This section provides a reference on the underlying classes that define the various objects in ISE.

The ISEEditor Object
Examples: $psISE.CurrentFile.Editor, $psISE.CurrentPowerShellTab.Output, $psISE.CurrentPowerShellTab.CommandPane.

The ISEFile Object
Examples: $psISE.CurrentFile, $psISE.PowerShellTabs.Files[0].

The ISEFileCollection Object
Examples: $psISE.PowerShellTabs.Files.

The ISEMenuItem Object
Examples: $psISE.CurrentPowerShellTab.AddOnsMenu , $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus[0].

The ISEMenuItemCollection Object
Example: $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.

The ObjectModelRoot Object
Example: The root $psISE object.

The ISEOptions Object
Examples: $psISE.Options, $psISE.Options.DefaultOptions.

The PowerShellTab Object
Examples: $psISE.CurrentPowerShellTab, $psISE.PowerShellTabs[0].

The PowerShellTabCollection Object
Example: $psISE.PowerShellTabs.

See Also

  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The ISEEditor Object

An ISEEditor object is an instance of the Microsoft.PowerShell.Host.ISE.ISEEditor class. The Output Pane and the Command Pane editors are ISEEditor objects. Each ISEFile object has an associated ISEEditor object. The following sections list the methods and properties of an ISEEditor object.

Methods

Clear()

Clears the text in the editor.fre

# Clears the text in the Output pane.
$psIse.CurrentPowerShellTab.Output.Clear()

EnsureVisible(int lineNumber)

Scrolls the editor so that the line corresponding to specified lineNumber is visible. It throws an exception if the specified lineNumber is outside the interval (1,last line number) which defines the range of valid line numbers.

lineNumber
Number of the line that is to be made visible.

# Scrolls the text in the Script Pane so that the fifth line is in view.
$psIse.CurrentFile.Editor.EnsureVisible(5)

Focus()

Sets the focus to the editor.

# Sets focus to the Output pane.
$psISE.CurrentPowerShellTab.Output.Focus()

GetLineLength(int lineNumber)

Gets the integer line length for the line specified by lineNumber.

lineNumber
Number of the line to get the length of.

Returns
The line length for the line at lineNumber.

# Gets the length of the first line in the text of the Command pane.
$psIse.CurrentPowerShellTab.CommandPane.GetLineLength(1)

InsertText(string text)

Replaces the selection with text or inserts text at the current caret position.

text
Text to insert.

See the Scripting Example later in this topic.

Select(int startLine, int startColumn, int endLine, int endColumn)

Selects the text from startLine, startColumn to endLine, endColumn.

startLine
Line where the selection starts.

startColumn
Column within startLine where the selection starts.

endLine
Line where the selection ends.

endColumn
Column within endLine where the selection ends.

See the Scripting Example later in this topic.

SetCaretPosition(int lineNumber, int columnNumber)

Sets the caret position at lineNumber and columnNumber. It throws an exception if either the lineNumber or the columnNumber are out of their respective valid ranges.

lineNumber
Caret line number.

columnNumber
Caret column number.

# Set the CaretPosition.
$firstfile=$psIse.CurrentFile
$firstFile.Editor.SetCaretPosition(5,1)

Properties

CaretColumn

Read-only property that gets the column number corresponding to the position of the caret.

# Get the CaretColumn.
$firstfile=$psIse.CurrentFile
$firstFile.Editor.CaretColumn

CaretLine

Read-only property that gets the number of the line that contains the caret.

# Get the CaretLine.
$firstfile=$psIse.CurrentFile
$firstFile.Editor.CaretLine

LineCount

Read-only property that gets the line count for the editor.

# Get the LineCount.
$firstfile=$psIse.CurrentFile
$firstFile.Editor.LineCount

SelectedText

Read-only property that gets the selected text from the editor.

See the Scripting Example later in this topic.

Text

Read/write property that gets the text in the editor.

See the Scripting Example later in this topic.

Scripting Example

# This illustrates how you can use the length of a line to select the entire line and shows how you can make it lowercase.
$myfile=$psIse.CurrentFile
# Start with clearing the text in the current file editor.
$myfile.Editor.Clear()

# Make sure the file has at least two lines of text.
$myfile.Editor.InsertText("LINE1 `n")
$myfile.Editor.InsertText("LINE2 `n")
$myfile.Editor.InsertText("LINE3 `n")
$myfile.Editor.InsertText("LINE4 `n")
$myfile.Editor.InsertText("LINE5 `n")

# You can use the GetLineLength method to get the length of the third line.
$endColumn= $myfile.Editor.GetLineLength(3)
# Select the text in the first three lines.
$myfile.Editor.Select(1,1,3,$endColumn + 1)
$selection = $myfile.Editor.SelectedText
# Clear all the text in the editor.
$myfile.Editor.Clear()
# Add the selected text back, but in lower case.
$myFile.Editor.InsertText($selection.ToLower())

See Also

  • The ISEFile Object
  • The PowerShellTab Object
  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The ISEFile Object

An ISEFile object represents a file in Windows PowerShell Integrated Scripting Environment (ISE). It is an instance of the Microsoft.PowerShell.Host.ISE.ISEFile class. This topic lists its member methods and member properties. The $psISE.CurrentFile and the files in the Files collection in a Powershell tab are instances of the Microsoft.PowerShell.Host.ISE.ISEFile class.

Methods

Save(System.Text.Encoding saveEncoding)

Saves the file to disk.

saveEncoding
Encoding to be used for the saved file.

Exceptions
  • System.IO.IOException: The file could not be saved.

# Save the file as ASCII.
$myfile=$psIse.CurrentFile
$myfile.Save( [System.Text.Encoding]::ASCII)

# Gets the current encoding.
$myfile=$psIse.CurrentFile
$myfile.Encoding

Save()

Saves the file.

Exceptions
  • System.IO.IOException: The file could not be saved.

# Explicitly save the file.
$psIse.CurrentFile.save()

SaveAs(string fileName)

Saves the file with the specified fileName.

fileName
The name to save the file as. The default encoding for the method is UTF-16.

Exceptions
  • System.ArgumentNullException: The fileName is null.

  • System.ArgumentException: The fileName is empty.

  • System.IO.IOException: The file could not be saved.

# Explicitly save the file.
$fullpath = "c:\temp\newname.txt"
$myfile=$psIse.CurrentFile
$myfile.SaveAs($fullPath)

SaveAs(string fileName, System.Text.Encoding saveEncoding)

Saves the file with the specified filename in the specified encoding.

fileName:
The name to save the file as. You can specify the full path name for the file.

saveEncoding
Encoding to save the file with.

Exceptions
  • System.ArgumentNullException: The fileName is null.

  • System.ArgumentException: The fileName is empty.

  • System.IO.IOException: The file could not be saved.

# Explicitly save the file as UTF8.
$fullpath = "c:\temp\newname.txt"
$myfile=$psIse.CurrentFile
$myfile.SaveAs($fullPath, [System.Text.Encoding]::UTF8)
# Gets the current encoding.
$myfile=$psIse.CurrentFile
$myfile.Encoding

Properties

DisplayName

Read-only property that gets the string that contains the display name of this file.

# Shows the display name of the file.
$psIse.CurrentFile.DisplayName

Editor

Read-only property that gets the editor that is used for the specified file.

# Gets the editor and the text.
$myfile=$psIse.CurrentFile
$myfile.Editor.Text

Encoding

Read-only property that gets the original file encoding. This is a System.Text.Encoding object.

# Shows the encoding for the file.
$myfile=$psIse.CurrentFile
$myfile.Encoding

FullPath

Read-only property that gets the string that specifies the full path of the opened file.

# Shows the full path for the file.
$myfile=$psIse.CurrentFile
$myfile.FullPath

IsSaved

Read-only Boolean property that returns true if the file has been saved since it was last modified.

# Determines whether the file has been saved since it was last modified.
$myfile=$psIse.CurrentFile
$myfile.IsSaved

IsUntitled

Read-only property that is true if the file has never been given a title.

# Determines whether the file has never been given a title.
$psISE.CurrentFile.IsUntitled
$psISE.CurrentFile.SaveAs("temp.txt")
$psISE.CurrentFile.IsUntitled

See Also

  • The ISEFileCollection Object
  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The ISEFileCollection Object

The ISEFileCollection object is a collection of ISEFile objects. The files collection associated with a PowerShellTab object is a member of this class. An example is the $psISE.CurrentPowerShellTab.Files collection.

Methods

Add()

Creates and returns a new untitled file and adds it to the collection. IsUntitled property of the newly created file is true.

# Adds a new file to the collection of files in the current PowerShell tab.
$newFile = $psISE.CurrentPowerShellTab.Files.Add()
# Add the date as the first line of text in the new file.
$newFile.Editor.Text = "#" + (Get-Date)

Add(string fullPath)

Adds a file specified by the fullPath parameter to the collection of files. IsUntitled property of the newly created file is false.

Note:

This method throws an exception if a relative path or a filename is used instead of the full path.

fullpath
The fully specified path of the file.

# Adds the file specified by its fullpath to the collection of files in the current PowerShell tab.
$psISE.CurrentPowerShellTab.Files.Add("$pshome\Examples\profile.ps1")

Remove(Microsoft.PowerShell.Host.ISE.ISEFile file)

Removes a specified file from the current PowerShell tab.

file
The ISEFile that you want to remove from the collection. If the file has not been saved, this method throws an exception. Use the following override to force the removal of an unsaved file.

# Removes the first opened file from the file collection associated with the current PowerShell tab.
$firstfile = $psISE.CurrentPowerShellTab.Files[0]
$psISE.CurrentPowerShellTab.Files.Remove($firstfile)

Remove(Microsoft.PowerShell.Host.ISE.ISEFile file, bool force)

Removes a specified file from the current PowerShell tab.

file
The ISEFile that you want to remove from the collection.

force
Boolean parameter that gives permission to remove the file even if it has not been saved since last use.

# Removes the first opened file from the file collection associated with the current PowerShell tab.
$firstfile = $psISE.CurrentPowerShellTab.Files[0]
$psISE.CurrentPowerShellTab.Files.Remove($firstfile, $true)

SetSelectedFile(Microsoft.PowerShell.Host.ISE.ISEFile selectedFile)

Selects the file specified by the selectedFile parameter.

selectedFile
The ISEFile that you would like to select.

# Selects the specified file.
$firstfile = $psISE.CurrentPowerShellTab.Files[0]
$psISE.CurrentPowerShellTab.Files.SetSelectedFile($firstfile)

See Also

  • The ISEFile Object
  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The ISEMenuItem Object

An ISEMenuItem object is an instance of the Microsoft.PowerShell.Host.ISE.ISEMenuItem class. All menu objects on the Add-ons menu are members of the Microsoft.PowerShell.Host.ISE.ISEMenuItem class.

Properties

DisplayName

Read-only property that gets the name of the menu.

# Get the display name of the Add-ons menu item
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Clear()
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Process",{get-process},"Alt+P")
$psISE.CurrentPowerShellTab.AddOnsMenu.DisplayName

Action

Read-only property that gets the script (block) to be invoked when the menu item is clicked.

# Get the action associated with the first submenu item.
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Clear()
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Process",{get-process},"Alt+P")
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus[0].Action
# Invoke the script associated with the first submenu item (Note the “.” At the beginning of the command).
# Invoke the action
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus[0].Action.Invoke()

Shortcut

Read-only property that gets the Windows input key gesture for the menu item.

# Get the shortcut for the first submenu item.
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Clear()
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Process",{get-process},"Alt+P")
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus[0].Shortcut

Submenus

Read-only property that gets the list of submenus of the menu item.

# List the submenus of the Add-ons menu
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Clear()
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Process",{get-process},"Alt+P")
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus

Scripting example

To better understand the use of the Add-ons menu and its scriptable properties, read through the following scripting example:

# This is a scripting example that shows the use of the Add-ons menu.
# Clear the Add-ons menu if one exists
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Clear()
# Add an Add-ons menu with an accessor.
# Note the use of “_”  as opposed to the “&” for mapping to the fast key letter for the menu item.
$menuAdded = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Process",{get-process},"Alt+P")
# Add a nested menu.
$parentAdded = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Parent",$null,$null)
$parentAdded.SubMenus.Add("_Dir",{dir},"Ctrl+Shift+D")

See Also

  • The ISEMenuItemCollection Object
  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The ISEMenuItemCollection Object

An ISEMenuItemCollection is a collection of ISEMenuItem objects. It is an instance of the Microsoft.PowerShell.Host.ISE.ISEMenuItemCollection class. An example is the $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus object that is used to customize the menus in the Windows PowerShell Integrated Scripting Environment (ISE).

Method

Add(string displayName, System.Management.Automation.ScriptBlock action, System.Windows.Input.KeyGesture shortcut)

Adds a menu item to the collection

displayname
The display name of the menu to be added.

action
The System.Management.Automation.ScriptBlock that specifies the action associated with this menu item.

shortcut
The shortcut for the action. It is of type System.Windows.Input.KeyGesture.

Returns:
The ISEMenuItem that was just added.

# Create an Add-ons menu with an accessor.
# Note the use of “_”  as opposed to the “&” for mapping to the accelerator for the menu item.
$menuAdded = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Process",{get-process},"Alt+P")

See Also

  • The ISEMenuItem Object
  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The ISEOptions Object

The Options object represents various settings for the Windows PowerShell ISE. It is an instance of the Microsoft.PowerShell.Host.ISE.ISEOptions class.

Methods

RestoreDefaultTokenColors()

Restores the default values of the token colors.

# Changes the color of the comments in the script to red and then restores it to its default value.
$psISE.Options.TokenColors["Comment"]="red"
$psISE.Options.RestoreDefaultTokenColors()

RestoreDefaults()

Restores the default values of all options settings. It also resets the behavior of various warning messages that provide the standard check box for "Don't show me this message again."

# Changes the background color in the Command Pane and then restores it to its default value.
$psISE.Options.CommandPaneBackground = "orange"
$psISE.Options.RestoreDefaults()

Properties

CommandPaneBackgroundColor

Read/write property that gets or sets the background color for the Command Pane editor. It is an instance of the System.Windows.Media.Color class.

# Changes the background color of the Command Pane to orange.
$psISE.Options.CommandPaneBackground = "orange"

CommandPaneUp

Read/write property that gets or sets a Boolean value that indicates whether the Command Pane is located above the Output Pane.

# Moves the Command Pane to the top of the screen.
$psISE.Options.CommandPaneUp  = $true

DebugBackgroundColor

Read/write property that gets or sets the background color for the debug text that appears in the Output Pane. It is an instance of the System.Windows.Media.Color class.

# Changes the background color for the debug text that appears in the Output Pane to blue.
$psISE.Options.DebugBackgroundColor ='#0000FF'

DebugForegroundColor

Read/write property that gets or sets the foreground color for the debug text that appears in the Output Pane. It is an instance of the System.Windows.Media.Color class.

# Changes the foreground color for the debug text that appears in the Output Pane to yellow.
$psISE.Options.DebugForegroundColor =”yellow”

DefaultOptions

Read-only property that gets the default values of the option settings.

# Displays the name of the default options.
$psISE.Options.DefaultOptions
# Here is a typical listing of the default options:
SelectedScriptPaneState       : Right
ShowToolBar                   : True
TokenColors                   : {[Attribute, #FFADD8E6], [Command, #FF0000FF], [Com
                                mandArgument, #FF8A2BE2], [CommandParameter, #FF000
                                080]...}
DefaultOptions                : Microsoft.PowerShell.Host.ISE.ISEOptions
FontSize                      : 12
FontName                      : Lucida Console
ErrorForegroundColor          : #FF0000FF
ErrorBackgroundColor          : #00FFFFFF
WarningForegroundColor        : #FFFF8C00
WarningBackgroundColor        : #00FFFFFF
VerboseForegroundColor        : #FF0000FF
VerboseBackgroundColor        : #00FFFFFF
DebugForegroundColor          : #FF0000FF
DebugBackgroundColor          : #00FFFFFF
OutputPaneBackgroundColor     : #FFF0F8FF
OutputPaneTextBackgroundColor : #FFF0F8FF
OutputPaneForegroundColor     : #FF000000
CommandPaneBackgroundColor    : #FFFFFFFF
ScriptPaneBackgroundColor     : #FFFFFFFF
ShowWarningForDuplicateFiles  : True
ShowWarningBeforeSavingOnRun  : True
UseLocalHelp                  : True
CommandPaneUp                 : False

ErrorBackgroundColor

Read/write property that gets or sets the background color for the error text that appears in the Output Pane. It is an instance of the System.Windows.Media.Color class.

# Changes the background color for the error text that appears in the Output Pane to black.
$psISE.Options.ErrorBackgroundColor="black"

ErrorForegroundColor

Read/write property that gets or sets the foreground color for the error text that appears in the Output Pane. It is an instance of the System.Windows.Media.Color class.

# Changes the foreground color for the error text that appears in the Output Pane to green.
$psISE.Options.ErrorForegroundColor =”green”

FontName

Read/write property that gets or sets the font name currently in use in the Script Pane, Command Pane and the Output Pane.

# Changes the font used in all the panes.
$psISE.Options.FontName = "courier new"

FontSize

Read/write property that gets or sets the font size (an integer) used in the Script Pane, Command Pane and the Output Pane. The valid range of values is (8, 32).

# Changes the font size in all the panes.
$psISE.Options.FontSize = 20

OutputPaneBackgroundColor

Read/write property that gets or sets the background color for the Output Pane itself. It is an instance of the System.Windows.Media.Color class.

# Changes the background color of the Output Pane to gold.
$psISE.Options.OutputPaneForegroundColor = "gold"

OutputPaneTextForegroundColor

Read/write property that changes the foreground color of the text in the Output Pane.

# Changes the foreground color of the text in the Output Pane to blue.
$psISE.Options.OutputPaneTextForegroundColor  = "blue"

OutputPaneTextBackgroundColor

Read/write property that changes the background color of the text in the Output Pane.

# Changes the background color of the Output Pane text to pink.
$psISE.Options.OutputPaneTextBackgroundColor = "pink"

ScriptPaneBackgroundColor

Read/write property that gets or sets the background color for files. It is an instance of the System.Windows.Media.Color class.

# Sets the color of the script pane background to yellow.
$psISE.Options.ScriptPaneBackgroundColor = ”yellow”

ScriptPaneForegroundColor

Read/Write property that gets or sets the foreground color for non-script files in the script pane. To set the foreground color for script files use the TokenColors property.

# Sets the foreground to color of non-script files in the script pane to green.
$psISE.Options.ScriptPaneBackgroundColor = ”green”

SelectedScriptPaneState

Read/write property that gets or sets the position of the Script Pane on the display. The possible values are “top”, “right”, and “Maximized”.

# Moves the Script Pane to the top
$psISE.Options.SelectedScriptPaneState = "Top"
# Moves the Script Pane to the right.
$psISE.Options.SelectedScriptPaneState = "Right"
# Maximizes the Script Pane
$psISE.Options.SelectedScriptPaneState = "Maximized"

ShowToolBar

Read/write Boolean property that determines whether the tool bar is visible.

# Show the tool bar.
$psISe.Options.ShowToolBar = $true

ShowWarningBeforeSavingOnRun

Read/write property that gets or sets a Boolean value that determines whether a warning message is displayed when a script is saved automatically before it is run.

# Sets the option to display a warning message
# when an attempt is made to save a script before running it.
$psISE.Options.ShowWarningBeforeSavingOnRun=$true

ShowWarningForDuplicateFiles

Read/write property that gets or sets a Boolean value that causes a warning message to appear when the same file is opened in different PowerShell tabs.

# Set the ShowWarningForDuplicateFiles property to true.
$psISE.Options.ShowWarningForDuplicateFiles = $true
# The following  message is displayed: “A copy of this file
# is open in another PowerShell Tab. Changes made to this
# file will affect all open copies.”

TokenColors

A property that gets a dictionary object that contains name/value pairs of token types and colors for the Command Pane and the Script Pane.

# Sets the color of commands to green.
$psISE.Options.TokenColors["Command"] = "green"
# Sets the color of keywords to magenta.
$psISE.Options.TokenColors["Keyword"] = "magenta"

UseLocalHelp

Read/write property that gets or sets a Boolean value that indicates whether the local help or the online help is displayed.

# Sets the option for the online help to be displayed.
$psISE.Options.LocalHelp=$false

VerboseBackgroundColor

Read/write property that gets or sets the background color for the verbose text that appears in the Output Pane. It is a System.Windows.Media.Color Object.

# Changes the background color for the verbose text that appears in the Output Pane to blue.
$psISE.Options.VerboseBackgroundColor ='#0000FF'

VerboseForegroundColor

Read/write property that gets or sets the foreground color for the verbose text that appears in the Output Pane. It is a System.Windows.Media.Color Object.

# Changes the foreground color for the verbose text that appears in the Output Pane to yellow.
$psISE.Options.VerboseForegroundColor =”yellow”

WarningBackgroundColor

Read/write property that gets or sets the background color for the warning text that appears in the Output Pane. It is a System.Windows.Media.Color Object.

# Changes the background color for the warning text that appears in the Output Pane to blue.
$psISE.Options.WarningBackgroundColor ='#0000FF'

WarningForegroundColor

Read/write property that gets or sets the foreground color for the warning text that appears in the Output Pane. It is a System.Windows.Media.Color Object.

# Changes the foreground color for the warning text that appears in the Output Pane to yellow.
$psISE.Options.WarningForegroundColor =”yellow”

See Also

  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The ObjectModelRoot Object

This topic describes an ObjectModelRoot object. It is an instance of the Microsoft.PowerShell.Host.ISE.ObjectModelRoot class. The $psISE object, which is the principal root object in Windows PowerShell Integrated Scripting Environment (ISE) belongs to this class. This topic describes the properties of the ObjectModelRoot object.

Properties

CurrentFile

A read-only property that gets or sets the file associated with this host object that currently has the focus.

CurrentPowerShellTab

A read-only property that gets the PowerShell tab that has the focus.

Options

A read-only property that gets the various options available to change settings in Windows PowerShell ISE.

PowerShellTabs

A read-only property that gets the collection of the PowerShell tabs that are open in Windows PowerShell ISE. By default, this object contains one PowerShell tab. However, you can add more PowerShell tabs to this object by using scripts or by using the menus in Windows PowerShell ISE.

See Also

  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The PowerShellTab Object

The PowerShell tab object embodies a Windows PowerShell execution environment. An example is $psISE.CurrentPowerShellTab.

Methods

The following are methods of the PowerShell tab object.

Invoke(System.Management.Automation.ScriptBlock script)

Executes the given script in the PowerShell tab.

Note:

This method only works on other PowerShell tabs, not on the PowerShell tab where it is run.

script:
Script to be executed.

# Manually create a second PowerShell tab before running this script.
# Return to the first tab and type
$secondTab = $psise.PowerShellTabs[1]
$secondTab.Invoke({dir})

Properties

AddOnsMenu

Read-only property that gets the Add-ons menu for the PowerShell Tab.

# Clear the Add-ons menu if one exists.
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Clear()
# Create an AddOns menu with an accessor.
# Note the use of “_”  as opposed to the “&” for mapping to the fast key letter for the menu item.
$menuAdded = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Process",{get-process},"Alt+P")
# Add a nested menu.
$parentAdded = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Parent",$null,$null)
$parentAdded.SubMenus.Add("_Dir",{dir},"Alt+D")
# Show the Add-ons menu on the current PowerShell tab.
$psISE.CurrentPowerShellTab.AddOnsMenu

CanInvoke

Read-only Boolean property that gets a true value if a script can be invoked with the Invoke(System.Management.Automation.ScriptBlock script) method.

# CanInvoke will be false if the PowerShell
# tab is running a script that takes a while, and you
# check its properties from another PowerShell tab. It is
# always false if checked on the current PowerShell tab.
# Manually create a second PowerShell tab before
# running this script.
# Return to the first tab and type
$secondTab = $psise.PowerShellTabs[1]
$secondTab.CanInvoke
$secondTab.Invoke({sleep 20})
$secondTab.CanInvoke

Commandpane

Read-only property that gets the Command Pane editor object.

# Gets the Command Pane editor.
$psISE.CurrentPowerShellTab.CommandPane

DisplayName

Read-write property that gets or sets the name of the PowerShell tab.

$newTab = $psise.PowerShellTabs.Add()
# Change the DisplayName of the new PowerShell tab.
$newTab.DisplayName="Brand New Tab"

ExpandedScript

Read/write Boolean property that determines whether the Script Pane is expanded or hidden.

# Toggle the expanded script property to see its effect.
$PSise.CurrentPowerShellTab.ExpandedScript=!$PSise.CurrentPowerShellTab.ExpandedScript

Files

Read-only property that gets the collection of script files that are open in the PowerShell tab.

$newFile = $psISE.CurrentPowerShellTab.Files.Add()
$newFile.Editor.Text = "a`r`nb"
# Gets the line count.
$newFile.Editor.LineCount

Output

Read-only property that gets the output editor.

# Clears the text in the output.
$psise.CurrentPowerShellTab.output.clear()

Prompt

Read-only property that gets the current prompt text.

# Gets the current prompt text.
$psISE.CurrentPowerShellTab.Prompt

StatusText

Read-only property that gets the PowerShellTab status text.

# Gets the current status text,
$psISE.CurrentPowerShellTab.StatusText

See Also

  • The PowerShellTabCollection Object
  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


The PowerShellTabCollection Object

The PowerShellTab collection object is a collection of PowerShellTab objects. It is an instance of Microsoft.PowerShell.Host.ISE.PowerShellTabs class. An example is the $psISE.PowerShellTabs object.

Methods

Add()

Adds a new PowerShell tab to the collection. It returns the newly added tab.

$psISE.PowerShellTabs.Add()

SetSelectedPowerShellTab(Microsoft.PowerShell.Host.ISE.PowerShellTab psTab)

Selects the PowerShell tab specified by pstab.

psTab
The PowerShell tab to select.

$newTab = $psISE.PowerShellTabs.Add()
# Change the DisplayName of the new PowerShell tab.
$newTab.DisplayName="Brand New Tab"

Remove(Microsoft.PowerShell.Host.ISE.PowerShellTab psTab)

Removes the tab specified by pstab.

psTab
The PowerShell tab to remove.

$newTab = $psISE.PowerShellTabs.Add()
Change the DisplayName of the new PowerShell tab.
$newTab.DisplayName="This tab will go away in 5 seconds"
sleep 5
$psISE.PowerShellTabs.Remove($newTab)

See Also

  • The PowerShellTab Object
  • Windows PowerShell ISE Object Model Reference
  • The ISE object hierarchy
  • The Windows PowerShell ISE Scripting Object Model


PowerShell.exe Console Help

Starts Windows PowerShell from the command line of another tool, such as Cmd.exe.

Syntax

PowerShell[.exe]
       [-PSConsoleFile <file> | -Version <version>]
       [-EncodedCommand <Base64EncodedCommand>]
       [-ExecutionPolicy <ExecutionPolicy>]
       [-File <filePath> <args>]
       [-InputFormat {Text | XML}]
       [-NoExit]
       [-NoLogo]
       [-NonInteractive]
       [-NoProfile]
       [-OutputFormat {Text | XML}]
       [-Sta]
       [-WindowStyle <style>]
       [-Command { - | <script-block> [-args <arg-array>]
                     | <string> [<CommandParameters>] } ]

PowerShell[.exe] -Help | -? | /?

Parameters

-EncodedCommand

Accepts a base-64-encoded string version of a command. Use this parameter to submit commands to Windows PowerShell that require complex quotation marks or curly braces.

-ExecutionPolicy

Sets the default execution policy for the session. This parameter does not change the Windows PowerShell execution policy that is set in the registry.

-File

Runs the specified script. Enter the script file path and any parameters.

-InputFormat

Describes the format of data sent to Windows PowerShell. Valid values are "Text" (text strings) or "XML" (serialized CLIXML format).

-NoExit

Does not exit after running startup commands.

-NoLogo

Hides the copyright banner at startup.

-NonInteractive

Does not present an interactive prompt to the user.

-NoProfile

Does not load the Windows PowerShell profile.

-OutputFormat

Determines how output from Windows PowerShell is formatted. Valid values are "Text" (text strings) or "XML" (serialized CLIXML format).

-PSConsoleFile

Loads the specified Windows PowerShell console file. To create a console file, use the Export-Console cmdlet in Windows PowerShell.

-Sta

Starts the shell using a single-threaded apartment.

-Version

Starts the specified version of Windows PowerShell. Enter a version number with the parameter, such as "-version 1.0".

-WindowStyle

Sets the window style to Normal, Minimized, Maximized or Hidden.

-Command

Executes the specified commands (and any parameters) as though they were typed at the Windows PowerShell command prompt, and then exits, unless NoExit is specified. The value of Command can be "-", a string. or a script block.

If the value of Command is "-", the command text is read from standard input.

Script blocks must be enclosed in braces ({}). You can specify a script block only when running PowerShell.exe in Windows PowerShell. The results of the script are returned to the parent shell as deserialized XML objects, not live objects.

If the value of Command is a string, Command must be the last parameter in the command , because any characters typed after the command are interpreted as the command arguments.

To write a string that runs a Windows PowerShell command, use the format:

"& {<command>}"

where the quotation marks indicate a string and the invoke operator (&) causes the command to be executed.

-Help, -?, /?

Shows this message. If you are typing a PowerShell.exe command in Windows PowerShell, prepend the command parameters with a hyphen (-), not a forward slash (/). You can use either a hyphen or forward slash in Cmd.exe.

EXAMPLES

PowerShell -PSConsoleFile sqlsnapin.psc1

PowerShell -version 1.0 -NoLogo -InputFormat text -OutputFormat XML

PowerShell -Command {Get-EventLog -LogName security}

PowerShell -Command "& {Get-EventLog -LogName security}"

# To use the -EncodedCommand parameter:
$command = "dir 'c:\program files' "
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand


Copyright Notice

This program is licensed.

Warning: This computer program is protected by copyright law and international treaties. Unauthorized reproduction or distribution of this program, or any portion of it, may result in severe civil and criminal penalties, and will be prosecuted to the maximum extent possible under the law.

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted in examples herein are fictitious. 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.

© 2009 Microsoft Corporation. All rights reserved.

Microsoft, and Microsoft Office Word, Microsoft Office Excel, Microsoft Visual Studio, Windows 7, Windows PowerShell, Windows Server 2008, Windows Server 2003, Windows XP, Windows Vista, and MSDN are trademarks of the Microsoft group of companies.

All other trademarks are property of their respective owners.